2011-03-15 93 views

回答

67

像这样:

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

或者

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

(这可能更快)

+12

使用“全部”而不是“任何”可能更容易阅读。在无法执行的情况下,您可能需要使用First()而不是[0](IEnumerable)。 if(list.All(o => o == list.First())){...} – 2014-09-08 21:00:57

+0

'list.Distinct()。Skip(1).Any()'与list.Distinct ).Count!= 1'对吗? – 2016-09-17 19:15:49

+0

@GraemeWicksted如果找到一个不匹配的项目,那么Any()的整个点就会更快。然后你停止评估清单。虽然是'!(list.Any(o => o!= list [0]))',但如果没有与第一个不同的项目 - 如果它们全部相同 – 2016-09-17 19:21:44

1

VB.NET版本:

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

或者

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

我创建主要用于可读性上任何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; 
    } 
0

这是一种选择,也:

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

它比if (list.Distinct().Skip(1).Any())更快,因为 if (list.Any(o => o != list[0])),但差别也执行是不重要的,所以我建议使用更可读的。

相关问题