Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DefaultIfEmpty in LINQ

Tags:

.net

linq

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.

like image 702
Nate Pet Avatar asked Jan 13 '12 16:01

Nate Pet


People also ask

What is default value LINQ?

The default value for reference and nullable types is null . The FirstOrDefault method does not provide a way to specify a default value.

Does DefaultIfEmpty return null?

DefaultIfEmpty() returns a new string collection with one element whose value is null because null is a default value of string.

Does LINQ query return null?

It will return an empty enumerable. It won't be null.

What is FirstOrDefault C#?

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.


1 Answers

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

like image 153
vc 74 Avatar answered Sep 24 '22 19:09

vc 74