Element Operator-ElementAt


The ElementAt operator returns the element at a given index in a sequence.


This sample prints the fourth number less that 5 in an integer array. The sample first uses a query expression then uses ElementAt to retrieve the fourth number from this sequence. Since ElementAt uses 0-based indexing, 3 is passed to the method to retrieve the fourth element.



Example:









using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace ConsoleApplication4

{

  class Program

  {

    static void Main(string[] args)

    {

     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);


      Console.ReadLine();

   }

 }

}



 


Output:


                    

Aspnet Related Tutorials

...more

New Aspnet Resources

...more

Copyright © 2012 VisualBuilder. All rights reserved