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

13 浏览
0 Comments

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

我有一个DateTime类型的List。我该如何使用LINQ查询检查所有项目是否相同?在任何时候,这个列表中可能有1、2、20、50或100个项目。

admin 更改状态以发布 2023年5月23日
0
0 Comments

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

if (items.AreAllSame()) ...

这是该方法的实现:

    /// 
    ///   Checks whether all items in the enumerable are same (Uses  to check for equality)
    /// 
    /// 
    /// The enumerable.
    /// 
    ///   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.
    /// 
    public static bool AreAllSame(this IEnumerable 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;
    }

0
0 Comments

像这样:

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

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

(这可能更快)

0