TakeWhile,但得到了停下它还元素 [英] TakeWhile, but get the element that stopped it also

查看:137
本文介绍了TakeWhile,但得到了停下它还元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

这篇关于TakeWhile,但得到了停下它还元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆