ElementAt

In this chapter you will learn:

  1. How to use ElementAt operator
  2. ElementAt vs ElementAtOrDefault
  3. Use ElementAt to print the fourth number less that 5 in an integer array

Get to know ElementAt operator

using System;/* j a va 2  s. c  o m*/
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Linq;

public class MainClass{
   public static void Main(){
            int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9};
            var query = numbers.ElementAt(4);
            Console.Write(query);
   }
}

ElementAt vs ElementAtOrDefault

ElementAt picks the nth element from the sequence:

using System;//j a  va 2s.  c o m
using System.Collections;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        int[] numbers = { 1, 2, 3, 4, 5 };
        int third = numbers.ElementAt(2);
        int tenthError = numbers.ElementAt(9);  // Exception 
        int tenth = numbers.ElementAtOrDefault(9);  // 0
        Console.WriteLine(third);
        Console.WriteLine(tenth);
    }
}

The output:

Get element after select

using System;//from  j ava2s  .  co m
using System.Collections.Generic;
using System.Linq;
using System.Text;

public class MainClass {
    public static void Main() {
        int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };

        int fourthLowNum = (
            from n in numbers
            where n < 5
            select n)
            .ElementAt(3); // 3 because sequences use 0-based indexing

        Console.WriteLine("Fourth number < 5: {0}", fourthLowNum);
    }
}

Next chapter...

What you will learn in the next chapter:

  1. How to use ElementAtOrDefault opeator
Home » C# Tutorial » Linq Operators
Aggregate
Aggregate with seed
Aggregate string value
All
Any
Average
Cast
Concat
Contains
Count
DefaultIfEmpty
Distinct
ElementAt
ElementAtOrDefault
Empty
Except
FindAll
First
FirstOrDefault
GroupBy
Intersect
Last
LastOrDefault
LongCount
Max
Min
OfType
OrderBy
OrderByDescending
Range
Repeat
Reverse
SelectMany
SequenceEqual
Single
SingleOrDefault
Skip
SkipWhile
Sum
Take
TakeWhile
ThenBy
ThenByDescending
ToArray
ToList
Zip