我想使用LINQ TakeWhile
函数LINQ到对象。不过,我也需要知道,爆发的功能,即第一个元素,其中的条件是不正确的第一个元素。
I'd like to use the LINQ TakeWhile
function on LINQ to Objects. However, I also need to know the first element that "broke" the function, i.e. the first element where the condition was not true.
有一个函数来获取所有不匹配的对象,加上第一次的呢?
Is there a single function to get all of the objects that don't match, plus the first that does?
例如,给定一组 {1,2,3,4,5}
,
mySet.MagicTakeWhile(x => x != 5);
=> {1,2,3,4,5}
我想你可以使用 SkipWhile < /一>,然后采取的第一要素。
I think you can use SkipWhile, and then take the first element.
var elementThatBrokeIt = data.SkipWhile(x => x.SomeThing).Take(1);
更新
如果你想有一个单一的扩展方法,你可以使用以下命令:
If you want a single extension method, you can use the following:
public static IEnumerable<T> MagicTakeWhile<T>(this IEnumerable<T> data, Func<T, bool> predicate) {
foreach (var item in data) {
yield return item;
if (!predicate(item))
break;
}
yield break;
}