Time for action – check out DefaultIfEmpty()

Follow the given steps:

  1. Copy the following as a query to LINQPad:
    public static List<double> GetLastWeekHumidity()
    {
      //Assume this is where we get the result from the Web Service
      List<double> humidityThisWeek = new List<double>();
      //Assume Web Service didn't return anything
      return humidityThisWeek.DefaultIfEmpty(80.0).ToList();
    }
    static void Main()
    {
      List<double> humidity = GetLastWeekHumidity();
      humidity.Dump("Humidity");
    }
  2. Run the query. You should see the following output:
    Time for action – check out DefaultIfEmpty()

What just happened?

DefaultIfEmpty() allows you to push only one default value in the source collection. In this case, 80.0 was pushed ...

Get .NET 4.0 Generics now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.