TakeWhile, but get the element that stopped it also

后端 未结 3 604
栀梦
栀梦 2021-01-17 08:50

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 elem

相关标签:
3条回答
  • 2021-01-17 09:33

    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.

    0 讨论(0)
  • 2021-01-17 09:34

    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;
        }
    }
    
    0 讨论(0)
  • 2021-01-17 09:37

    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() })
    
    0 讨论(0)
提交回复
热议问题