ExtensionMethod.NET Home of 818 C#, Visual Basic, F# and Javascript extension methods

DefaultIfEmpty

The provided DefaultIfEmpty will only accept an instance of T as the default value. Sometimes you need the default to be an IEnumerable<T>.

Source

public static IEnumerable<TSource> DefaultIfEmpty<TSource>(this IEnumerable<TSource> source, IEnumerable<TSource> defaultValue)
{
    return (source != null && source.Any()) ? source : defaultValue;
}

Example

var coverageList = Coverages.Where(x => x.Equals(coverage, planCode, stateCode))
.DefaultIfEmpty(Coverages.Where(x => x.Equals(coverage, defaultPlanCode, stateCode)))
.DefaultIfEmpty(Coverages.Where(x => x.Equals(coverage, defaultPlanCode, defaultStateCode)))

Author: ThatChuckGuy

Submitted on: 14 sep 2013

Language: C#

Type: System.Collections.Generic.IEnumerable<T>

Views: 3436