繁体   English   中英

检查列表中的所有项目是否相同

[英]Check if all items are the same in a List

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

谢谢

像这样:

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

要么

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

(这可能更快)

我创建了简单的扩展方法,主要是为了可读性,适用于任何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;
    }

VB.NET版本:

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

要么

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

这也是一个选择:

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

它比if (list.Distinct().Skip(1).Any())更快,并且执行类似if (list.Any(o => o != list[0])) ,但是,区别在于不重要,所以我建议使用更易读的。

我的变种:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM