Getting the first element from a sequence in LINQ C#

Say you have the following object sequence:

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}

If you just want to get the very first element from this sequence with no query then you can use the First operator:

Singer singer = singers.First();

This will select Freddie Mercury from the list. You can also send an item selector to get the first element which matches the query:

Singer singer = singers.First(s => s.Id == 2);

…which returns Elvis Presley.

A caveat is that the First operator throws an InvalidOperationException if there’s no single matching record:

Singer singer = singers.First(s => s.Id == 100);

To avoid this scenario you can use the FirstOrDefault operator which returns the default value of the required object if there’s no matching one. Therefore “singer” in the above example will be null:

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

…which prints “No such singer”.

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: Logo

You are commenting using your 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


Once Upon a Camayoc

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

%d bloggers like this: