【问题标题】:c# Check if all strings in list are the same [duplicate]c#检查列表中的所有字符串是否相同[重复]
【发布时间】:2011-07-13 15:24:40
【问题描述】:

可能重复:
Check if all items are the same in a List

我有一个清单:

{string, string, string, string}

我需要检查此列表中的所有项目是否相同然后返回true,如果不返回false。

我可以用 LINQ 做到这一点吗?

【问题讨论】:

    标签: c# linq


    【解决方案1】:
    var allAreSame = list.All(x => x == list.First());
    

    【讨论】:

    • 除了list.First() 在每次迭代中都如此有效地被遍历两次?
    • @DavidClarke:假设这是 LINQ to objects,list 只是一个物化集合,如列表或数组:由于list.First 返回第一个元素,它不会遍历列表,所以:不,列表只遍历一次。然而,更笼统地说,你是对的:如果list 是一个非物化可枚举,那么每次调用First 都需要执行所有代码(例如访问数据库或执行复杂的 Where 或 OrderBy 语句)才能获得至少是第一个元素。在这种情况下,最好调用一次list.First 并存储结果
    【解决方案2】:
    var allAreSame = list.Distinct().Count() == 1;
    

    或者更优化一点

    var allAreSame = list.Count == 0 || list.All(x => x == list[0]);
    

    【讨论】:

    • 实际上,对于基本类型的紧凑列表,甚至是短字符串(缩写、简单单词等),至少为了可读性,我不会反对 list.Distinct().Count() == 1;list.All(current => current == list.First())
    【解决方案3】:

    这个怎么样:

        string[] s = { "same", "same", "same" };
        if (s.Where(x => x == s[0]).Count() == s.Length)
        {
            return true;
        }
    

    【讨论】:

    • 这是 lambda 表达式吗?
    【解决方案4】:
    var hasIdenticalItems = list.Count() <= 1 || list.Distinct().Count() == 1;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-05-21
      • 1970-01-01
      • 2022-12-01
      • 2023-03-31
      • 2022-12-01
      • 2018-10-17
      • 1970-01-01
      相关资源
      最近更新 更多