假设我有以下简单类的集合:
public class MyEntity
{
public string SubId { get; set; }
public System.DateTime ApplicationTime { get; set; }
public double? ThicknessMicrons { get; set; }
}
我需要搜索整个集合,寻找具有空ThicknessMicrons
值的5个连续(不是5个,但连续5个)实体。连续性将基于ApplicationTime属性。该集合将在该属性上进行分类。
如何在Linq查询中执行此操作?
答案 0 :(得分: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个连续匹配,则只能找到一个子序列。