TakeWhile,但得到了停下它还元素它还、得到了、元素、TakeWhile

2023-09-04 07:24:02 作者:禽兽放开那怪物

我想使用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}

推荐答案

我想你可以使用 Sk​​ipWhile < /一>,然后采取的第一要素。

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;
}