2011-07-26 57 views

回答

2

你可以定義一些擴展方法:

static bool LessThan<T>(this IEnumerable<T> enumerable, int count, Func<T, bool> predicate) 
{ 
    int found = 0; 
    foreach (var item in enumerable) 
    { 
     if (predicate(item)) 
     { 
      found++; 
      if (found >= count) 
       return false; 
     } 
    } 
    return true; 
} 

static bool MoreThan<T>(this IEnumerable<T> enumerable, int count, Func<T, bool> predicate) 
{ 
    int found = 0; 
    foreach (var item in enumerable) 
    { 
     if (predicate(item)) 
     { 
      found++; 
      if (found > count) 
       return true; 
     } 
    } 
    return false; 
} 

,然後用它們像這樣:

var col = new[] { 1, 6, 4, 8, 3, 5, 1, 7 }; 
var res1 = col.MoreThan(2, c => c == 1); //false 
var res2 = col.MoreThan(1, c => c == 1); //true 
var res3 = col.LessThan(4, c => c > 5); //true 
var res4 = col.LessThan(3, c => c > 5); //false 
+0

非常好,雖然可能應該(發現>計數)在第二個在第一和(發現> =計數)。 –

+0

這將使當匹配元素的量等於要搜索量,這沒有任何意義的名字「每種不超過」和「人數超過」他們返回true。 – Kylar

7

您可以使用此表達式:.Skip(limit).Any()相當於Count() > limit。但如果您的清單是ICollection,則更優選Count()

謂詞版本:

public static bool MoreThan<TSource>(this IEnumerable<TSource> source, 
    Func<TSource, bool> predicate, int limit) 
{ 
    int i = 0; 

    foreach (var item in source) 
    { 
     if (predicate(item)) 
     { 
      i++; 

      if (i > limit) 
      { 
       return true; 
      } 
     } 

    } 

    return false; 
} 
+0

+1:這比我的方法好。 –

+0

@Daniel,謝謝! –

+0

很好的實施,謝謝。 –