September 23, 2008

I love FirstOrDefault

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


No comments: