LINQ DefaultIfEmpty method in C#

canro91 profile image Cesar Aguirre Originally published at canro91.github.io ・1 min read

LINQ DefaultIfEmpty extension method returns a collection containing a single element if the given collection is empty. Otherwise, it returns the same collection.

Example: Find all the movies with score greater than 9. Otherwise, return you’re all-time favorite movie.

var movies = new List<Movie>
    new Movie("Titanic”, 5),
    new Movie("Back to the Future”, 7),
    new Movie("Black Hawk Down”, 6)

var movieToWatch = movies.Where(movie => movie.Score >= 9)
                    .DefaultIfEmpty(new Movie("Fifth Element", 10))

// Movie { Name="Fifth Element", Score=10 }
Enter fullscreen mode Exit fullscreen mode

If I had to implement it on my own, it would be like this:

public static IEnumerable<T> DefaultIfEmpty<T>(this Enumerable<T> source, T @default)
    => source.Any() ? source : new[]{ @default };
Enter fullscreen mode Exit fullscreen mode

Source: Enumerable.DefaultIfEmpty Method


Editor guide