LINQ – Element Operations





5.00/5 (1 vote)
Element operations in LINQ
In the last blog post, we discussed about Click Event and Change Event in jQuery. You can read that article here. In this article, we will go over Element Operations in LINQ.
Different Element Operations in LINQ are as follows:
ElementAt
/ElementAtOrDefault
- Returns the element at a specified index- Look at the example code below. We have a sequence of 2
string
s,Hello
andWorld
. If we writenotEmpty.ElementAt(1)
, we will getWorld
as output. So this is zero based indexing andWorld
is the element at position1
.
- Look at the example code below. We have a sequence of 2
First
/FirstOrDefault
- Returns the first element of a collection- You may use this Element Operation quite frequently with queries, particularly when working with databases. So using this operation, instead of getting back an
IEnumerable
collection, we will just get back one element reference.
- You may use this Element Operation quite frequently with queries, particularly when working with databases. So using this operation, instead of getting back an
Last
/LastOrDefault
– Returns the last element of a collectionSingle
/SingleOrDefault
- Returns a single element- This Element Operator returns a single element instead of getting
IEnumerable
collection. So it is almost similar toFirst
/FirstOrDefault
operator. The primary difference is that, withSingle
, if there isn’t just one result in the sequence, it will throw an exception.
- This Element Operator returns a single element instead of getting
Example
sting[] empty={ };
sting[] notEmpty={ “Hello”,“World”};
var result=empty.FirstOrDefault(); //null
result=notEmpty.Last(); //World
result=notEmpty.ElementAt(1); //World
result=empty.First(); //InvalidOperationException
result=notEmpty.Single(); //InvalidOperationException
result=notEmpty.First(s=>s.StartsWith(“W”));
Reference
- Arun Ramachandran (http://BestTEchnologyBlog.Com)