How to Access the First and Last Element using LINQ


If you have a Collection (sequence) of objects and you want to access the First and Last element using LINQ. you can use First and Last query operators as shown in the following code.

The Customer objects collection used as sample

List<Customer> customers = new List<Customer>();

customers.Add(new Customer { Id = 10, Name = "Simon" });
customers.Add(new Customer { Id = 11, Name = "Peter" });
customers.Add(new Customer { Id = 12, Name = "Mark" });
customers.Add(new Customer { Id = 13, Name = "James" });

To get the First element use First operator

Customer firstCustomer = customers.First();

To get the Last element use Last operator

Customer lastCustomer = customers.Last();

 

 

About author


User avatar

Waqas Anwar

Founder of EzzyLearning.com, Senior Consultant, Microsoft .NET and Web Technologies

Comments