Updated on Kisan Patel
The Element operators in LINQ return just one element. So These are a group of extension methods that can be used to select single item from a list.
The ElementAt, ElementAtOrDefault, First, FirstOrDefault, Last, LastOrDefault and SingleOrDefault clauses are termed as the Element operators.
The ElementAt
clause returns the element at a specified index in a collection that implements IEnumerable
.
For example, to retrieve the fifth position value in the list you can pass four to the method’s argument; passing zero would return the first item.
NorthwindEntities _db = new NorthwindEntities(); var customer = _db.Customers.AsEnumerable().ElementAt(5); Console.WriteLine(customer.ContactTitle + " - " + customer.Country);
the above code will produce below output…
The ElementAtOrDefault clause returns the element at a specified index in a collection or the default value if the index out of range.
ElementAtOrDefault
handles an out-of-range access without throwing an exception.For Example,
NorthwindEntities _db = new NorthwindEntities(); var customer = _db.Customers.AsEnumerable().ElementAtOrDefault(500); string ContactTitle = (customer == null) ? "Out of Index" : customer.ContactTitle; Console.WriteLine(ContactTitle);
the above C# code will produce below output…
The First clause returns the first element of the collection. If there is no such element then First throws an InvalidOperationException
.
For Example,
NorthwindEntities _db = new NorthwindEntities(); var customer = _db.Customers.AsEnumerable().First(); Console.WriteLine(customer.ContactTitle + " - " + customer.Country);
the above C# code will produce below output…
The FirstOrDefault clause returns the first element of a collection or throw an exception if there is no such element.
The Last and LastOrDefault standard query operator is similar to First and FirstOrDefault. But the Last or LastOrDefault clause returns the last element from a collection.
For Example,
NorthwindEntities _db = new NorthwindEntities(); var customer = _db.Customers.AsEnumerable().Last(); Console.WriteLine(customer.ContactTitle + " - " + customer.Country);
the above C# code will produce below output…
The Single clause returns the only element of the collection that satisfies the given condition. In the case of Single, when the sequence is empty or has more than one item, the method fails.
The SingleOrDefault
method provides similar functionality to the Single standard query operator but returns a default value if the source sequence is empty.
For Example,
NorthwindEntities _db = new NorthwindEntities(); var customers = _db.Customers.ToList(); var customer = customers.Where(x => x.CustomerID == "HUNGC") .SingleOrDefault(x => x.Country == "USA"); if(customer != null) Console.WriteLine(customer.ContactTitle + " - " + customer.Country);
the above C# code will produce below output…