Retrieving Elements from Collection in C#

CsharpProgrammingServer Side Programming

Let us see an example of a list collection.

We have set the elements −

List<int> list = new List<int>();
list.Add(20);
list.Add(40);
list.Add(60);
list.Add(80);

Now let’s say we need to retrieve the first element from the list. For that, set the index like this −

int a = list[0];

The following is an example showing how to retrieve elements from a list collection −

Example

using System;
using System.Collections.Generic;

class Demo {

   static void Main(String[] args) {
      List<int> list = new List<int>();
      list.Add(20);
      list.Add(40);
      list.Add(60);
      list.Add(80);

      foreach (int val in list) {
         Console.WriteLine(val);
      }

      int a = list[0];
      Console.WriteLine("First element: "+a);
   }
}
raja
Published on 14-Aug-2018 16:59:34
Advertisements