You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#遍历字符串列表查找不同值的代码实现问题

问题原因分析
  • 初始化的currencyTypes是空列表,循环不会触发执行
  • 条件判断存在语法错误:if判断条件没有用括号包裹,[i]不是合法取值,没有明确和基准值对比的逻辑
  • 控制台输出方法大小写错误,C#中标准写法为Console.WriteLine
  • 没有提前终止逻辑:检测到差异后不需要继续遍历剩余元素
实现方案

方案1:原生循环实现(无第三方依赖)

取列表第一个元素作为基准值,遍历后续所有元素和基准值对比,检测到差异立即终止遍历:

List<string> currencyTypes = new List<string> {"GBP", "GBP", "GBP", "USD"};

// 空列表或仅有1个元素默认判定为所有元素相同,可根据业务需求调整逻辑
if (currencyTypes.Count > 1)
{
    string baseCurrency = currencyTypes[0];
    for (int i = 1; i < currencyTypes.Count; i++)
    {
        if (currencyTypes[i] != baseCurrency)
        {
            Console.WriteLine("currencies are different");
            // 检测到差异直接跳出循环,无需继续遍历
            break;
        }
    }
}

方案2:LINQ简便写法

引入System.Linq命名空间后,直接用All()方法判断所有元素是否和第一个元素一致:

using System.Linq;

// ...其他代码
List<string> currencyTypes = new List<string> {"GBP", "GBP", "GBP", "USD"};

if (currencyTypes.Any() && !currencyTypes.All(c => c == currencyTypes[0]))
{
    Console.WriteLine("currencies are different");
}

内容的提问来源于stack exchange,提问作者dros

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.13 02:03:00