Explain about DefaultIfEmpty() in LINQ

Using Linq DefaultIfEmpty() extension method

By Using DefaultIfEmpty() extension method you can check the sequence for empty and return something for it and do some manipulation on it afterwards.

For example

1
2
var numbers = new int[] {1,2,3,4,5,6,7};
Console.WriteLine(numbers.DefaultIfEmpty().Sum());
If the sequence is empty it will return 0 otherwise it will sum and return that.

By Default if you want to return some value other then 0 it will return that as well


1
Console.WriteLine(numbers.DefaultIfEmpty(100).Sum());
In this case it will return 100 if the sequence is empty.

0 comments:

Post a Comment