Safely dereferencing FirstOrDefault call in Linq c#

后端 未结 3 1040
谎友^
谎友^ 2021-02-12 22:08

For brevity\'s sake in my code, i\'d like to be able to do the following: having a collection, find the first element matching a lambda expression; if it exists, return the valu

3条回答
  •  天涯浪人
    2021-02-12 22:29

    Why not just do:

    stuff.Where(s => s.contains("bvi"))
         .Select(s => s.ToUpper())
         .FirstOrDefault()
    

    If you have a "non-default default", you can do:

    stuff.Where(s => s.contains("bvi"))
         .Select(s => s.ToUpper())
         .DefaultIfEmpty("Something Else")
         .First()
    

提交回复
热议问题