Retrieve elements in a collection in C#

WBOY
Release: 2023-08-21 20:45:02
forward
1574 people have browsed it

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);
Copy after login

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];
Copy after login

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);
   }
}
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template