FirstOrDefault: Default value other than null

后端 未结 11 1150
-上瘾入骨i
-上瘾入骨i 2020-12-12 21:37

As I understand it, in Linq the method FirstOrDefault() can return a Default value of something other than null. What I haven\'t worked out is wha

11条回答
  •  醉梦人生
    2020-12-12 21:58

    You can also do this

        Band[] objects = { new Band { Name = "Iron Maiden" } };
        first = objects.Where(o => o.Name == "Slayer")
            .DefaultIfEmpty(new Band { Name = "Black Sabbath" })
            .FirstOrDefault();   // returns "Black Sabbath" 
    

    This uses only linq - yipee!

提交回复
热议问题