Selecting the only element from a single element sequence in .NET C#

Say you have the following Singer object and sequence of Singers:

public class Singer
{
	public int Id { get; set; }
	public string FirstName { get; set; }
	public string LastName { get; set; }
	public int BirthYear { get; set; }
}

IEnumerable<Singer> singers = new List<Singer>() 
		{
			new Singer(){Id = 1, FirstName = "Freddie", LastName = "Mercury", BirthYear=1964}
			, new Singer(){Id = 2, FirstName = "Elvis", LastName = "Presley", BirthYear = 1954}
			, new Singer(){Id = 3, FirstName = "Chuck", LastName = "Berry", BirthYear = 1954}
			, new Singer(){Id = 4, FirstName = "Ray", LastName = "Charles", BirthYear = 1950}
			, new Singer(){Id = 5, FirstName = "David", LastName = "Bowie", BirthYear = 1964}
		};

You can use the Single operator to get the only result of an element selector. You can write in two different ways which are functionally the same:

Singer singer = singers.Where(s => s.Id == 2).Single();
Console.WriteLine(singer.LastName);

…or…

Singer singer = singers.Single(s => s.Id == 2);
Console.WriteLine(singer.LastName);

Both will select Elvis Presley. The query was successful because the element selector lambda expression resulted in a sequence with a single element. The Single operator extracted that one element from the – very short – sequence. If it finds more than one element matching the filter or if it finds nothing then it will throw an exception:

Singer singer = singers.Single(s => s.Id == 200);
Singer singer = singers.Single(s => s.Id < 4);

The first line throws an invalid operation exception as the resulting sequence contained 0 elements. The second line again throws the same type of exception because the element selector yielded more than one element.

You can use the operator SingleOrDefault to avoid the problem encountered with 0 elements:

Singer singer = singers.SingleOrDefault(s => s.Id == 200);
Console.WriteLine(singer == null ? "No such singer" : singer.LastName);

View the list of posts on LINQ here.

About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.

%d bloggers like this: