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 default value for reference and nullable types is null . The FirstOrDefault method does not provide a way to specify a default value.
DefaultIfEmpty() returns a new string collection with one element whose value is null because null is a default value of string.
It will return an empty enumerable. It won't be null.
FirstOrDefault. Returns the first element of a collection, or the first element that satisfies a condition. Returns a default value if index is out of range. First and FirstOrDefault has two overload methods. The first overload method doesn't take any input parameter and returns the first element in the collection.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With