Home  >  Article  >  Backend Development  >  Retrieve elements in a collection in C#

Retrieve elements in a collection in C#

WBOY
WBOYforward
2023-08-21 20:45:021523browse

Let’s look at an example of a list collection.

We set the element −

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. To do this, set the index as follows −

int a = list[0];

The following is an example that shows how to retrieve elements from a collection of lists −

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

The above is the detailed content of Retrieve elements in a collection in C#. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete