【问题标题】:Check if all items are the same in a List检查列表中的所有项目是否相同
【发布时间】:2011-03-15 03:21:42
【问题描述】:

我有一个 List(Of DateTime) 项目。如何使用 LINQ 查询检查所有项目是否相同?在任何给定时间,列表中可能有 1、2、20、50 或 100 个项目。

【问题讨论】:

    标签: c# vb.net list linq-to-objects


    【解决方案1】:

    像这样:

    if (list.Distinct().Skip(1).Any())
    

    或者

    if (list.Any(o => o != list[0]))
    

    (可能更快)

    【讨论】:

    • 使用“All”而不是“Any”可能更容易阅读。如果无法执行列表访问(IEnumerable),您可能还想使用 First() 而不是 [0]。 if (list.All(o => o == list.First())) { ... }
    • list.Distinct().Skip(1).Any() 与 list.Distinct().Count != 1 没有什么不同,对吧?
    • @GraemeWicksted 如果发现一个项目不匹配,Any() 的全部意义在于更快。然后你停止评估列表。稍微清楚一点的是!(list.Any(o => o != list[0])),如果没有与第一个不同的项目,即如果它们都相同
    • @Simon_Weaver Any() 用于查找至少 1 个匹配项,而 All() 用于确保所有项目匹配。在任何一种情况下,如果在 All 中遇到不匹配或在 Any 中找到匹配,它们将停止迭代。所以!(list.Any(o => o != list[0])); 和list.All(o => o == list[0]); 将始终具有相同的迭代次数。因此,两者的执行时间大致相同。附言你是对的,因为 list.Distinct().Skip(1).Any() 类似于 list.Distinct().Count != 1 只是要知道 Count 可能比具有 > 1 个元素的 Any(甚至可能在这种情况下)慢。
    • 但是 count 必须遍历整个不同的列表。如果您有 2 套以上,则速度较慢。
    【解决方案2】:

    我创建了简单的扩展方法,主要是为了可读性,它适用于任何 IEnumerable。

    if (items.AreAllSame()) ...
    

    以及方法实现:

        /// <summary>
        ///   Checks whether all items in the enumerable are same (Uses <see cref="object.Equals(object)" /> to check for equality)
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="enumerable">The enumerable.</param>
        /// <returns>
        ///   Returns true if there is 0 or 1 item in the enumerable or if all items in the enumerable are same (equal to
        ///   each other) otherwise false.
        /// </returns>
        public static bool AreAllSame<T>(this IEnumerable<T> enumerable)
        {
            if (enumerable == null) throw new ArgumentNullException(nameof(enumerable));
    
            using (var enumerator = enumerable.GetEnumerator())
            {
                var toCompare = default(T);
                if (enumerator.MoveNext())
                {
                    toCompare = enumerator.Current;
                }
    
                while (enumerator.MoveNext())
                {
                    if (toCompare != null && !toCompare.Equals(enumerator.Current))
                    {
                        return false;
                    }
                }
            }
    
            return true;
        }
    

    【讨论】:

    • 不错!只是想知道空列表的实现。我不确定我是否会假设一个空列表意味着“所有人都是一样的”——感觉就像消费者要处理的一个案例,所以我想如果列表为空,我会扔掉。 “苹果是一样的吗?没有线索,因为篮子里没有苹果”
    【解决方案3】:

    我的变种:

    var numUniques = 1;
    var result = list.Distinct().Count() == numUniques;
    

    【讨论】:

    • 我喜欢这个,与 skip1/any 解决方案相比,它的可读性很强并且显示出意图。
    【解决方案4】:

    这也是一个选项:

     if (list.TrueForAll(i => i.Equals(list.FirstOrDefault())))
    

    它比 if (list.Distinct().Skip(1).Any()) 快,并且性能类似于 if (list.Any(o =&gt; o != list[0])),不过差别不大,建议用可读性更强的。

    【讨论】:

      【解决方案5】:

      VB.NET 版本:

      If list.Distinct().Skip(1).Any() Then
      

      或者

      If list.Any(Function(d) d <> list(0)) Then
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-08-29
        • 2011-11-21
        • 2011-04-20
        • 2023-03-03
        • 2015-07-05
        • 2016-02-16
        • 1970-01-01
        相关资源
        最近更新 更多