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.<
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.
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