DefaultIfEmpty MethodUse the DefaultIfEmpty extension method from System.Linq to get a default value if no elements are present.
This page was last reviewed on Jan 10, 2024.
DefaultIfEmpty. This method handles empty collections in a special way. It returns a default value, not an error. It is part of the System.Linq namespace.
With DefaultIfEmpty, we replace empty collections with a singleton collection that may be more compatible with other parts of the C# program.
Example. The concept of DefaultIfEmpty is simple: it replaces an empty collection with a collection of one default value. Remember that the default value of int is 0.
Thus DefaultIfEmpty on a List int yields a List with one element, and its value is 0.
Also You can pass an argument to DefaultIfEmpty. This will become the value that is used in the singleton collection's value.
using System; using System.Collections.Generic; using System.Linq; // Empty list. List<int> list = new List<int>(); var result = list.DefaultIfEmpty(); // One element in collection with default(int) value. foreach (var value in result) { Console.WriteLine(value); } result = list.DefaultIfEmpty(-1); // One element in collection with -1 value. foreach (var value in result) { Console.WriteLine(value); }
0 -1
Usage. If you call DefaultIfEmpty on a null reference, you will get a NullReferenceException. DefaultIfEmpty can only be used to handle empty collections.
Tip It is useful if in other locations in your program, empty collections cannot be used.
Argument version. The version that receives an argument may be more useful. You can use a custom default object that handles the situation where there are no elements present.
Note In the book Refactoring, this technique is referred to as a null object (see Introduce Null Object).
A summary. We saw the behavior of DefaultIfEmpty. The method changes empty collections to collections with one element. With the optional parameter, you can use custom default objects.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Jan 10, 2024 (edit).
© 2007-2024 Sam Allen.