Click here to Skip to main content
15,867,765 members
Articles / All Topics
Technical Blog

Returning a Single Element With LINQ First and LINQ Single

Rate me:
Please Sign up or sign in to vote.
1.20/5 (2 votes)
2 Jun 20091 min read 15.6K   1   2
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:

<span style="color: #606060">   1:</span> <span style="color: #0000ff">public</span> <span style="color: #0000ff">class</span> Person
<span style="color: #606060">   2:</span> {
<span style="color: #606060">   3:</span>     <span style="color: #0000ff">public</span> <span style="color: #0000ff">string</span> Name { get; set; }
<span style="color: #606060">   4:</span>     <span style="color: #0000ff">public</span> <span style="color: #0000ff">int</span> Age { get; set; }
<span style="color: #606060">   5:</span>     <span style="color: #0000ff">public</span> <span style="color: #0000ff">bool</span> Leader { get; set; }
<span style="color: #606060">   6:</span> }

And let's load up some sample data:

<span style="color: #606060">   1:</span> Person[] people = <span style="color: #0000ff">new</span> Person[] {
<span style="color: #606060">   2:</span>     <span style="color: #0000ff">new</span> Person { Name = <span style="color: #006080">"Blue"</span>, Age = 25, Leader = <span style="color: #0000ff">true</span> },
<span style="color: #606060">   3:</span>     <span style="color: #0000ff">new</span> Person { Name = <span style="color: #006080">"Gold"</span>, Age = 16, Leader = <span style="color: #0000ff">false</span> },
<span style="color: #606060">   4:</span>     <span style="color: #0000ff">new</span> Person { Name = <span style="color: #006080">"Red"</span>, Age = 27, Leader = <span style="color: #0000ff">false</span> },
<span style="color: #606060">   5:</span>     <span style="color: #0000ff">new</span> Person { Name = <span style="color: #006080">"Green"</span>, Age = 14, Leader = <span style="color: #0000ff">false</span>}
<span style="color: #606060">   6:</span> };

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

<span style="color: #606060">   1:</span> Person leader = people.Where(p => p.Leader == <span style="color: #0000ff">true</span>).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":

<span style="color: #606060">   1:</span> Person leader2 = people.First(p => p.Leader == <span style="color: #0000ff">true</span>);
<span style="color: #606060">   2:</span> Person leader3 = people.Single(p => p.Leader == <span style="color: #0000ff">true</span>);

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:

<span style="color: #606060">   1:</span> Person firstChild1 = people.First(p => p.Age < 18);
<span style="color: #606060">   2:</span> 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.


License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Software Developer (Senior)
United States United States
Winner - Best Mobile App - AT&T Developer Summit, Las Vegas, 2013

My personal resume can be found at: http://www.philippiercedeveloper.com

My game portfolio can be found at: http://www.rocketgamesmobile.com

About Philip Pierce:

I am a software developer with twenty years experience in game development, mobile, web, desktop, server, and database. My extensive background highlights an expertise in rapid application development using the latest Microsoft, Mobile, and Game Development technologies, along with the ability to create AI for games and business software, redesign existing software, develop multi-threaded software, and create client/server applications.

Comments and Discussions

 
GeneralMy vote of 1 Pin
Not Active3-Jun-09 2:35
mentorNot Active3-Jun-09 2:35 
GeneralMy vote of 2 Pin
Jon Artus3-Jun-09 2:19
Jon Artus3-Jun-09 2:19 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.