2011-03-15 178 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])),但差別也執行是不重要的,所以我建議使用更可讀的。

相關問題