2011-08-18 49 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