LINQ – Element Operations


In the last blog post, we have 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 following:

  • ElementAt/ElementAtOrDefault  Returns the element at a specified index.
    • Look at the example code below. We have a sequence of 2 strings, Hello and World. If we write notEmpty.ElementAt(1), we will get World as output. So this is zero based indexing and World is the element at the position 1.
  • First/FirstOrDefault Returns the first element of a collection.
    • You may use this Element Operation quite frequently with queries, particularly when work with databases. So using this operation, instead of getting back an IEnumerable collection, we will just get back one element reference.
  • Last/LastOrDefaultReturns the last element of a collection.
  • Single/SingleOrDefault  Returns a single element.
    • This Element Operator returns a single element instead of getting IEnumerable collection. So it is almost similar to First/FirstOrDefault operator. The primary difference is that, with Single, if there isn’t just one result in the sequence, it will throw an exception.


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


Reference: Arun Ramachandran (http://BestTEchnologyBlog.Com)

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s