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");

Chris Brandsma

  • http://colinjack.blogspot.com Colin Jack

    You read my mind, was thinking about how much I loved this little piece of code last week.

  • http://elegantcode.com trasa

    I have caught bugs by using SingleOrDefault(), usually with comments around the usage like “there can never be more than 1 Foo’s matching in this collection,” (whoops)

  • Jason

    Dang, trasa beat me to my comment. I’ve had one project in particular where SingleOrDefault() caught some false assumptions about a sproc. On the other hand SingleOrDefault() doesn’t return as soon as an item is found (on IEnumerable) so it might be slightly slower on large collections. Not sure about the execution times of the two methods on LTS. I’m curious now, so I might check it out.

    My personal favorite Linq extension methods are of the filtering and aggregate types. I use list.Any(item => item.IsSomethingTrue) and list.Max(item => item.Property) a lot.

  • Jamie

    Example 1: return list.Count > 0 ? list[0] : null;

    Example 2: return list.Find(“whatever”);
    or, if List.Find(T item) did not yet exist, return list.Contains(“whatever”) ? “whatever” : null;

    Are not all that worse than the FirstOrDefault code, are they?

  • http://www.elegantcode.com Jarod

    I think its important to point out that FirstOrDefault or SingleOrDefault are extension methods of IEnumerable, and Enumerate when called.

    @Jamie

    The example above is using List, so your arguments are fair. However, if you where working with IEnumerable, you would be forced to enumerate somehow before your example would work. (such as calling ToList())

    In that case, FirstOrDefault does it all in one shot, is is much simpler, and doesnt force you to copy to the whole collection to a list when all you want is one object.

  • http://blog.cwa.me.uk/2008/09/24/the-morning-brew-186/ Reflective Perspective – Chris Alcock » The Morning Brew #186

    [...] I love FirstOrDefault – Chris Brandsma shows how Linq’s FirstOrDefault extension method can improve your code. [...]

  • http://www.jphamilton.net J.P. Hamilton

    Learn something new every day. I didn’t know the method could take a lambda…guess I wasnt paying attention. I thought you had to do this:

    return list.Where(blah blah).FirstOrDefault();

    Nice.

  • http://codemonkeylabs.com/blog/weekly-web-nuggets-31/ Code Monkey Labs

    Weekly Web Nuggets #31…

    General Commented-Out Code & Broken Windows : Jan Van Ryswyck says what everyone is thinking – commented code introduces a lot of mess into your code. There’s a reason we use version control systems…just delete that code! I Love …

  • Amila Rajapakse

     love C# :)

  • Anonymous

    myTable.firstOrDefault

    or myTable.Take(1).FirstOrDefault ? for select top 1 * from myTable 

  • 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?

blog comments powered by Disqus