C# Enumerable DefaultIfEmpty(IEnumerable, TSource)
Description
Returns the elements of the specified sequence or the specified value in a singleton collection if the sequence is empty.
Syntax
public static IEnumerable<TSource> DefaultIfEmpty<TSource>(
this IEnumerable<TSource> source,
TSource defaultValue
)
Parameters
TSource
- The type of the elements of source.source
- The sequence to return the specified value for if it is empty.defaultValue
- The value to return if the sequence is empty.
Returns
Returns the elements of the specified sequence or the specified value in a singleton collection if the sequence is empty.
Example
The following code example demonstrates how to use the DefaultIfEmpty(IEnumerable, TSource) method and specify a default value.
//from w ww. ja v a2 s.co m
using System;
using System.Linq;
using System.Collections.Generic;
public class MainClass{
public static void Main(String[] argv){
Pet defaultPet = new Pet { Name = "Default", Age = 0 };
List<Pet> pets1 =
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 pets1.DefaultIfEmpty(defaultPet))
{
Console.WriteLine("Name: {0}", pet.Name);
}
List<Pet> pets2 = new List<Pet>();
foreach (Pet pet in pets2.DefaultIfEmpty(defaultPet))
{
Console.WriteLine("\nName: {0}", pet.Name);
}
}
}
class Pet{
public string Name { get; set; }
public int Age { get; set; }
}
The code above generates the following result.