DefaultIfEmpty in LINQ

后端 未结 2 1067
别跟我提以往
别跟我提以往 2021-01-07 16:24

Can somebody explain how DefaultIfEmpty() can be used in LINQ. I have ready some material but still need something solid to see what the use of it is.<

2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-07 16:53

    The difference is the DefaultIfEmpty returns a collection of objects while FirstOrDefault returns an object. If there were no results found DefaultIfEmpty still returns an Enumerable with a single item that has its default value, whereas FirstOrDefault returns T itself.

    You use DefaultIfEmpty if you need always need a collection result, for instance to create outer joins. You use FirstOrDefault if you always need an object (not a collection) result, for instance if you want to get the first item (or only item) when searching for something like an ID or unique email, and want to return the default empty item if the item you were searching for was not found.

提交回复
热议问题