LINQ equivalent of List.Find()?

前端 未结 3 777
情书的邮戳
情书的邮戳 2021-02-03 12:51

I\'m looking at some code that takes an IEnumerable and converts it to a List so it can use List.Find(predicate):

var myEnumerable = .         


        
相关标签:
3条回答
  • 2021-02-03 13:33

    Or you can do the following way:

    var match = myEnumerable.Where(value => value.Aaa == aaa && value.Bbb == bbb)
                            .FirstOrDefault();
    
    0 讨论(0)
  • 2021-02-03 13:37

    The LINQ equivelent would be to use FirstOrDefault:

    var match = myEnumerable.FirstOrDefault(value => value.Aaa == aaa && value.Bbb == bbb);
    
    0 讨论(0)
  • 2021-02-03 13:53

    Just for reference, here is a table of some old .NET 2 style List<> instance methods, and their equivalent extension methods in Linq:

    METHOD IN List<>                              METHOD IN Linq
    ------------------------------------------------------------------------------------------
    
    list.Contains(item)                           query.Contains(item)
    
    list.Exists(x => x.IsInteresting())           query.Any(x => x.IsInteresting())
    list.TrueForAll(x => x.IsInteresting())       query.All(x => x.IsInteresting())
    
    list.Find(x => x.IsInteresting())             query.FirstOrDefault(x => x.IsInteresting())
    list.FindLast(x => x.IsInteresting())         query.LastOrDefault(x => x.IsInteresting())
    
    list.FindAll(x => x.IsInteresting())          query.Where(x => x.IsInteresting())
    
    list.ConvertAll(x => x.ProjectToSomething())  query.Select(x => x.ProjectToSomething())
    

    Of course some of them are not entirely equivalent. In particular Linq's Where and Select use deferred execution, while FindAll and ConvertAll of List<> will execute immediately and return a reference to a new List<> instance.

    FindLast will often be faster than LastOrDefault because FindLast actually searches starting from the end of the List<>. On the other hand LastOrDefault(predicate) always runs through the entire sequence (starting from the first item), and only then returns the most "recent" match.

    0 讨论(0)
提交回复
热议问题