DefaultIfEmpty in LINQ

后端 未结 2 1066
别跟我提以往
别跟我提以往 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.

    0 讨论(0)
  • 2021-01-07 17:03

    It basically returns a collection with a single element in case the source collection is empty.

    var numbers = new int[] {1, 2, 3};
    var aNumber = numbers.First();
    

    returns 1

    but

    var numbers = new int[];
    var aNumber = numbers.DefaultIfEmpty(12).Single();
    

    returns 12 as the collection is empty

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