【问题标题】:Loop through list of strings to find different values遍历字符串列表以查找不同的值
【发布时间】:2021-09-15 18:04:45
【问题描述】:

我有一个填充了不同值的列表:

例如

{GBP, GBP, GBP, USD} 

到目前为止我有这个:

List<string> currencyTypes = new List<string>();

for (int i = 0; i < currencyTypes.Count; i++)
{
    if currencyTypes[i] != [i]
        console.writeline("currencies are different");
}

因此,如果列表具有所有相同的条目,则不应触发 if 语句

e,g {GBP, GBP, GBP, GBP}

但是,如果任何值与其他值不同,则 if 语句应该注意到差异并触发。

但这不起作用。

有什么想法吗?

【问题讨论】:

    标签: c# string list loops


    【解决方案1】:

    您应该首先对数据进行分组,然后根据组找到结果。

    例如

        List<string> currencyTypes = new List<string>() {"USD", "GBP", "GBP", "GBP" };
    
        // group list items
        var typeGroup = currencyTypes.GroupBy(t => t);
        
        if (typeGroup.Count() > 1)
            Console.WriteLine("currencies are different");
        // .    
        // .
        
        // also you can check what item is unique   
        foreach (var t in typeGroup.Where(g => g.Count() == 1 ))
        {
            Console.WriteLine($"{t.Single()} is different");
        }
    

    【讨论】:

      【解决方案2】:

      您可以使用 LINQ 测试所有条目是否相同

      if (currencyTypes.Distinct().Count() > 1) {
          Console.WriteLine("currencies are different");
      }
      

      长列表的效率略高:

      if (currencyTypes.Count > 1 && currencyTypes.Distinct().Skip(1).Any()) {
          Console.WriteLine("currencies are different");
      }
      

      这更有效,因为 Any 最多迭代一个元素,而 Count 迭代整个列表。

      【讨论】:

        【解决方案3】:

        首先,您的列表是空的。也许是为了这个例子。如果没有,请使用数据对其进行初始化。但是,将第 3 行和第 5 行修改为此问题即可解决。

        for (int i = 1; i < currencyTypes.Count; i++)
        {
            if (currencyTypes[i] != currencyTypes[i-1])
           .... 
         } 
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2017-04-22
          • 1970-01-01
          • 2021-08-06
          • 2020-10-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多