Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   




C# - ACCESSING LIST


Accessing the elements of the 'List' using Indexes


We have the List with three values, 5, John and C#. And we want to access the second element i.e. John.


Example :



using System.Collections.Generic;
    
public class MyApplication
{
    public static void Main(string[] args)
    {
        var x = new List<object>(){5, "John", "C#"};
        System.Console.WriteLine(x[1]);  
    }    
}


Output :



  John

So, in the above code we have created a List and initialised to the variable x.


var x = new List<object>(){5, "John", "C#"};

Now, let us see, how the values are positioned in the List

C_Sharp

So, as we can see the elements are positioned as 0, 1 and 2. And if we want to access the second element, we can refer to the position 1 using the square brackets (i.e. x[1]).


And the print statement prints the value of the second element of the List (i.e. John).


System.Console.WriteLine(x[1]);