Retrieving an element from a sequence with an index in LINQ C#
July 8, 2014 Leave a comment
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} };
Say you want to get to the second element of the singers sequence. You can use the ElementAt operator to achieve that. As all arrays and lists are 0 based, then the second element has index = 1:
Singer singer = singers.ElementAt(1); Console.WriteLine(singer.LastName);
The operator has found Elvis Presley. If there’s no element at the specified index then an ArgumentOutOfRangeException is thrown. To avoid that you can use the ElementAtOrDefault operator instead:
Singer singer = singers.ElementAtOrDefault(100); Console.WriteLine(singer == null ? "No such singer" : singer.LastName);
…which prints “No such singer”.
View the list of posts on LINQ here.