Element Operators in LINQ

Element operators operate over a sequence and return only one element. There are four main types of element operators in LINQ. They are as follows

  • First
  • Last
  • Single
  • ElementAt

First and Last

The First operator returns the first element of the sequence while Last operator returns the last element. If lambda expression is passed to these operators they will return First and Last element that meets the condition specified by the lambda expression.

There are two variants of these operators as well: FirstOrDefault and LastOrDefault. The First and Last operators will through exception if no matching elements are found where as the FirstOrDefault and LastOrDefault methods will return the default values of the type if no matching element is found. Have a look at this example.

´╗┐using System;
using System.Collections.Generic;
using System.Linq;

namespace CSharpTutorials {
    class Tutorial {
        static void Main() {
            string[] sequence1 = { "Joseph", "Juana", "Sara", "Mike", "Angel", "Victoria" };

            String output = sequence1.First();
            Console.WriteLine(output); // Joseph will be printed.

            // First element with K in it
            output = sequence1.First(e=>e.Contains("k"));
            Console.WriteLine(output); // Mike will be printed.

            output = sequence1.Last();
            Console.WriteLine(output); // Victoria will be printed

            // Last element with e in it
            output = sequence1.Last(e=>e.Contains("e"));
            Console.WriteLine(output); // Angel will be printed

            Console.ReadKey();
        }
    }
}

Download the code

Single & ElementAt

Single operator returns single value that matches the condition specified by the lambda expression. In case if no element matches the condition, the application throws error. To avoid an exception an alternate of Single operator SingleOrDefault can be used. Similarly, the ElementAt Operator returns the element at the specified index. Have a look at the following example.

´╗┐using System;
using System.Collections.Generic;
using System.Linq;

namespace CSharpTutorials {
    class Tutorial {
        static void Main() {
            string[] sequence1 = { "Joseph", "Juana", "Sara", "Mike", "Angel", "Victoria" };

            String output = sequence1.Single(e=>e.Contains("l"));
            Console.WriteLine(output); // Angel will be printed.

            output = sequence1.ElementAt(2);
            Console.WriteLine(output); // Sara Value will be printed

            Console.ReadKey();
        }
    }
}

Download the code

<<< Aggregate Methods in LINQSet Operators in LINQ >>>
Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .