2010-06-23 79 views
3

我寫了一個自定義LINQ擴展方法,該方法將TakeWhile()方法擴展爲包容性的,而不是在謂詞爲假時排除。自定義包容TakeWhile(),有沒有更好的方法?

 public static IEnumerable<T> TakeWhile<T>(this IEnumerable<T> source, Func<T, bool> predicate, bool inclusive) 
     { 
      source.ThrowIfNull("source"); 
      predicate.ThrowIfNull("predicate"); 

      if (!inclusive) 
       return source.TakeWhile(predicate); 

      var totalCount = source.Count(); 
      var count = source.TakeWhile(predicate).Count(); 

      if (count == totalCount) 
       return source; 
      else 
       return source.Take(count + 1); 
     } 

雖然這個工作,我敢肯定有一個更好的方式來做到這一點。我相當肯定,這在延遲執行/加載方面不起作用。

ThrowIfNull()ArgumentNullException檢查

社會可以提供一些一些提示或重新寫一個擴展方法? :)

回答

10

你是對的;這對推遲執行不友好(調用Count需要完整枚舉源)。

你可以,但是,這樣做:

public static IEnumerable<T> TakeWhile<T>(this IEnumerable<T> source, Func<T, bool> predicate, bool inclusive) 
{ 
    foreach(T item in source) 
    { 
     if(predicate(item)) 
     { 
      yield return item; 
     } 
     else 
     { 
      if(inclusive) yield return item; 

      yield break; 
     } 
    } 
} 
+0

好極了!一個更好的解決方案,我的:) – 2010-06-23 22:53:55

+0

這很漂亮。 – 2012-10-05 16:12:53

+0

這太棒了。特別是當你需要一個具有倒置邏輯的TakeWhile時,即當謂詞是'false'時取一切。 – silkfire 2016-10-06 06:25:22

相關問題