我有一个 list (简体)
[Kind] [Name]
null E
null W
4 T
5 G
6 Q
null L
null V
7 K
2 Z
0 F
我需要{E,L}->此处的Kind == null和下一个Kind == null的项目
假设有一个ID递增且顺序排列。
在Linq,这种前瞻性可能吗?
最佳答案
像这样?
void Main()
{
List<SomeClass> list = new List<SomeClass>() {
new SomeClass() { Kind = null, Name = "E" },
new SomeClass() { Kind = null, Name = "W" },
new SomeClass() { Kind = 4, Name = "T" },
new SomeClass() { Kind = 5, Name = "G" },
...
};
var query = list.Where ((s, i) =>
!s.Kind.HasValue &&
list.ElementAtOrDefault(i + 1) != null &&
!list.ElementAt(i + 1).Kind.HasValue);
}
public class SomeClass
{
public int? Kind { get; set; }
public string Name { get; set; }
}
编辑:偷@Jeff Marcado的解决方案,以实现类似于上述用法的扩展方法,但要干净一点,并且不能使您处理索引:
public static IEnumerable<TSource> WhereWithLookahead<TSource>(this IEnumerable<TSource> source, Func<TSource, TSource, bool> predicate) where TSource : class
{
using(var enumerator = source.GetEnumerator())
{
if (!enumerator.MoveNext())
{
//empty
yield break;
}
var current = enumerator.Current;
while (enumerator.MoveNext())
{
var next = enumerator.Current;
if(predicate(current, next))
{
yield return current;
}
current = next;
}
if (predicate(current, null))
{
yield return current;
}
}
}
// Use:
var query2 = list.WhereWithLookahead((current, next) =>
!current.Kind.HasValue &&
(next != null) &&
next.Kind.HasValue);
关于c# - LINQ:前瞻性状况,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11276885/