I love FirstOrDefault

September 23rd, 2008

I know all of you who are using C# 3.0 (released with .Net 3.5) have found some of the goodness that is in System.Linq.  My current favorite is FirstOrDefault.  This little extension method returns the first element of a list, or the first element that meets a criteria, or returns the object’s default value.   If you have done work with generics, you should be familiar with default already.  Default for nullable types is null.  Default for value types is…it depends on the type.

Example 1:

Here is my old code:

   1: List<string> list = LoadList();
   2: if (list.Count > 0)
   3:    return list[0];
   4: else
   5:    return null;

This is the new code with FirstOrDefault:

   1: List<string> list = LoadList();
   2: return list.FirstOrDefault();

 

Example 2:

Old code:

   1: List<string> list = LoadList();
   2: foreach(var s in list)
   3: {
   4:   if (s == "My special text")
   5:   {
   6:     return s;
   7:   }
   8: }
   9: return null;

New Code:

   1: List<string> list = LoadList();
   2: return list.FirstOrDefault( s => s == "My special text");

  • Zgraf

    Rock on.  Thanks for explaining this with a clean, simple C# example.

  • Boris Juraga

    So far i have had 1 trouble with it in .NET CF 3.5

    List containing:
    aaaaa
    aabbb
    abbcc
    abccc
    abcdd

    var one = (from p in List where p.StartsWith(“abcd”) select p).FirstOrDefault();

    one is null.

    How is that possible?