[HowTo] LINQ - First Start # DefaultIfEmpty Operator

This HowTo introduces how to use the DefaultIfEmpty operator.

Introduction

The DefaultIfEmpty operator can be used to return a single element sequence with a default value if the used sequence of elements is empty. The use of the DefaultIfEmpty operator allows handling empty and non-empty sequences without checking them for their population by using additional lines of code or activity modelings.

Example

I – Input P – Processing O – Output
{"A1","A2"} Get all Items starting with B
OR return a single item sequence with a “NotFound” item
{"NotFound"}
{"A1","A2"} Get all Items starting with A
OR return a single item sequence with a “NotFound” item
{"A1","A2"}
{15,20,25} Get all items < 10
OR return a single item sequence with a -1 item
{-1}
{15,20,25} Get all items > 10
OR return a single item sequence with a -1 item
{15,20,25}

Implementation

Method Syntax

arrSValues | String( ) - a String Array =  {"A1","A2"}

arrSResult = arrSValues.Where(Function(x) x.StartsWith("B").DefaultIfEmpty("NotFound").ToArray()
arrSResult = arrSValues.Where(Function(x) x.StartsWith("A").DefaultIfEmpty("NotFound").ToArray()
Visuals

grafik

arrNValues | Int32( ) - an int32 Array = {15,20,25}

arrNResult = arrNValues.Where(Function(x) x < 10).DefaultIfEmpty(-1).ToArray()
arrNResult = arrNValues.Where(Function(x) x > 10).DefaultIfEmpty(-1).ToArray()
Visuals

grafik

Query Syntax

The DefaultIfEmpty operator is not available as a clause for the query syntax

Comparison to other operators

Various operators (e.g. Where) are used to return a set with none, one or many elements. With the DefaultIfEmpty operator it can be achieved that never an empty (no element) set is returned. A corresponding cardinality check is obsolete. The default value can be influenced because it can be defined explicitly.

In selected scenarios a similar behavior can be achieved with a XXXOrDefault().
Example:
grafik

But in this case, FirstOrDefault(…) does not return a set of items, as the singular data type is returned (in the above example: int32). Also, the default value of the datatype is used (int32 = 0) and cannot be redefined. In a large number of data types, however, the default value would be NULL.

:bulb: With the evolution of .Net (starting with .Net 6) e.g. the FirstOrDefault Operator has been a method signature, which allows the definition of a custom default value

Visuals - .Net6 and higher - Custom Default Value on FirstOrDefault

grafik

Out of the Box Default Values

DataType Default Value
Boolean false
int32 0
Double 0
String NULL
DataRow NULL
DateTime [01/01/0001 00:00:00]

Conclusion

  • The DefaultIfEmpty operator can thus be used to ensure that a set with at least one item is always returned.
  • The DefaultValue can be influenced.

References

Documentations:

Questions

For questions on your use case open a new topic and get individual support

2 Likes