2011-08-18 50 views
1

說我有下面的簡單類的集合:LINQ查詢所需要的 - 尋找數據的模式

public class MyEntity 
{ 
    public string SubId { get; set; } 
    public System.DateTime ApplicationTime { get; set; } 
    public double? ThicknessMicrons { get; set; } 
} 

我需要通過整個集合尋找5 連續(不共5個搜索,但連續5次)具有空值的實體。連續性將基於ApplicationTime屬性。該集合將在該屬性上進行排序。

我該如何在Linq查詢中做到這一點?

回答

4

你可以很容易地編寫自己的擴展方法:

public static IEnumerable<IEnumerable<T>> FindSequences<T>(this IEnumerable<T> sequence, Predicate<T> selector, int size) 
{ 
    List<T> curSequence = new List<T>(); 
    foreach (T item in sequence) 
    { 
     // Check if this item matches the condition 
     if (selector(item)) 
     { 
      // It does, so store it 
      curSequence.Add(item); 

      // Check if the list size has met the desired size 
      if (curSequence.Count == size) 
      { 
       // It did, so yield that list, and reset 
       yield return curSequence; 
       curSequence = new List<T>(); 
      } 
     } 
     else 
     { 
      // No match, so reset the list 
      curSequence = new List<T>(); 
     } 
    } 
} 

現在你可以說:

var groupsOfFive = entities.OrderBy(x => x.ApplicationTime) 
          .FindSequences(x => x.ThicknessMicrons == null, 5); 

注意這將返回長度5.您的所有子序列可以測試像這樣的存在:

bool isFiveSubsequence = groupsOfFive.Any(); 

另一個重要的注意事項是,如果您有9個連續匹配,則只會找到一個子序列。

+0

不錯的工作。我會盡快嘗試。 – Hosea146