Linq首先跳过其中(linq到对象) [英] Linq skip first where (linq to objects)
问题描述
我需要跳过与谓词匹配的第一个元素作为linq查询.据我所知,我能做到的就是这样:
I have the need to skip the first element that matches a predicate as a linq query. So far as I can tell the best I can do is something like this:
var list = new [] {1,2,3,4,5,6,7,8,9};
var skippedFirstOdd = false;
var skipFirstEvenNumber = list.SkipWhile(number =>
{
if(number % 2 != 0)
{
skippedFirst = true;
return true;
}
else
{
return false;
}
});
哪个(我认为)可以工作,但不是很优雅.有没有更清洁的方法来实现这一目标?
Which works (I think), but isn't very elegant. Is there a cleaner way to achieve this?
推荐答案
您可以编写一个迭代器块扩展方法:
You could write an iterator-block extension method:
public static IEnumerable<T> SkipFirstMatching<T>
(this IEnumerable<T> source, Func<T, bool> predicate)
{
if (source == null)
throw new ArgumentNullException("source");
if (predicate == null)
throw new ArgumentNullException("predicate");
return SkipFirstMatchingCore(source, predicate);
}
private static IEnumerable<T> SkipFirstMatchingCore<T>
(IEnumerable<T> source, Func<T, bool> predicate)
{
bool itemToSkipSeen = false;
foreach (T item in source)
{
if (!itemToSkipSeen && predicate(item))
itemToSkipSeen = true;
else yield return item;
}
}
并将其用作:
var list = new [] { 1,2,3,4,5,6,7,8,9 };
var skipFirstEvenNumber = list.SkipFirstMatching(i => i % 2 == 0);
顺便说一句,您当前的代码似乎根本不正确.该变量称为skipFirstEvenNumber
,但是查询正在跳过奇数数字.其次,您似乎试图利用副作用来使查询正常工作,但是您只是设置标志变量,而不是读取它.因此,您当前的代码应该像普通的SkipWhile
一样工作.
By the way, your current code doesn't seem correct at all. The variable is called skipFirstEvenNumber
, but the query is skipping odd numbers. Secondly, you appear to try to be using a side-effect to get the query to work, but you are only setting the flag variable, not reading it. Consequently, your current code should work just like a normal SkipWhile
.
编辑:急于进行参数验证.
EDIT: Made argument-validation eager.
这篇关于Linq首先跳过其中(linq到对象)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!