TakeWhile, but get the element that stopped it also

我与影子孤独终老i 提交于 2019-12-04 02:59:47

问题


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?

For example, given the set {1, 2, 3, 4, 5, 6, 7, 8},

mySet.MagicTakeWhile(x => x != 5);

=> {1, 2, 3, 4, 5}


回答1:


I think you can use SkipWhile, and then take the first element.

var elementThatBrokeIt = data.SkipWhile(x => x.SomeThing).Take(1);

UPDATE

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



回答2:


LINQ to Objects doesn't have such an operator. But it's straightforward to implement a TakeUntil extension yourself. Here's one such implementation from moreLinq.




回答3:


Just for fun:

var a = new[] 
    {
        "two",
        "three",
        "four",
        "five",
    };
  Func<string, bool> predicate = item => item.StartsWith("t");      
  a.TakeWhile(predicate).Concat(new[] { a.SkipWhile(predicate).FirstOrDefault() })


来源:https://stackoverflow.com/questions/11883469/takewhile-but-get-the-element-that-stopped-it-also

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!