65.9K
CodeProject is changing. Read more.
Home

Returning a Single Element With LINQ First and LINQ Single

starIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIconemptyStarIcon

1.20/5 (2 votes)

Jun 3, 2009

1 min read

viewsIcon

16003

Sometimes you have a list, and you need to return a single element from the list. There are several ways to get the element to return. Below are two ways using LINQ with Lambda expressions. Consider the following class: 1: public class Person 2: { 3: public strin

Sometimes you have a list, and you need to return a single element from the list. There are several ways to get the element to return. Below are two ways using LINQ with Lambda expressions.

Consider the following class:

   1: public class Person
   2: {
   3:     public string Name { get; set; }
   4:     public int Age { get; set; }
   5:     public bool Leader { get; set; }
   6: }

And let's load up some sample data:

   1: Person[] people = new Person[] {
   2:     new Person { Name = "Blue", Age = 25, Leader = true },
   3:     new Person { Name = "Gold", Age = 16, Leader = false },
   4:     new Person { Name = "Red", Age = 27, Leader = false },
   5:     new Person { Name = "Green", Age = 14, Leader = false}
   6: };

Now what we could do to find the leader (the assumption is that there is always only one leader):

   1: Person leader = people.Where(p => p.Leader == true).ToArray()[0];

The result of the people.Where() is an IEnumerable<Person>.  And you can't just index the first element of that – so you convert it to an array and index that instead.

LINQ provides two methods to perform this type of query without the need of having an intermediate array -- "First" and "Single":

   1: Person leader2 = people.First(p => p.Leader == true);
   2: Person leader3 = people.Single(p => p.Leader == true);

The difference between the two is that First grabs the first item it finds.  The Single method expects only a single matching item and will throw an exception if it finds more than one.  In this case, there is only one Person in the array that has Leader set to true so both of these lines of code produce the same result.

However, in the situation below:

   1: Person firstChild1 = people.First(p => p.Age < 18);
   2: Person firstChild2 = people.Single(p => p.Age < 18);

The first line will succeed.  The second line will fail since there are two people that are under 18.