Getting the last element from a sequence with 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 last element from this sequence with no query then you can use the Last operator:

Singer singer = singers.Last();
Console.WriteLine(singer.LastName);

This will select David Bowie from the list. You can also send an item selector to get the last element which matches the query:

Singer singer = singers.Last(s => s.BirthYear == 1954);
Console.WriteLine(singer.LastName);

…which returns Chuck Berry.

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

Singer singer = singers.Last(s => s.BirthYear == 2000);

To avoid this scenario you can use the LastOrDefault 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.LastOrDefault(s => s.BirthYear == 2000);
Console.WriteLine(singer == null ? "No such singer" : singer.LastName);

…which yields “No such singer”.

You can view all LINQ-related posts on this blog here.

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: