C# Enumerable DefaultIfEmpty(IEnumerable)
Description
Returns the elements of the specified sequence or the type parameter's default value in a singleton collection if the sequence is empty.
Syntax
public static IEnumerable<TSource> DefaultIfEmpty<TSource>(
this IEnumerable<TSource> source
)
Parameters
TSource
- The type of the elements of source.source
- The sequence to return a default value for if it is empty.
Returns
Returns the elements of the specified sequence or the type parameter's default value in a singleton collection if the sequence is empty.
Example
The following code examples demonstrate how to use DefaultIfEmpty(IEnumerable) to provide a default value in case the source sequence is empty.
//from w w w.j a v a 2 s. c o m
using System;
using System.Linq;
using System.Collections.Generic;
public class MainClass{
public static void Main(String[] argv){
List<Pet> pets =
new List<Pet>{ new Pet { Name="A", Age=8 },
new Pet { Name="B", Age=4 },
new Pet { Name="C", Age=1 } };
foreach (Pet pet in pets.DefaultIfEmpty())
{
Console.WriteLine(pet.Name);
}
}
}
class Pet{
public string Name { get; set; }
public int Age { get; set; }
}
The code above generates the following result.