Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Get or set the element at specified index in Collection in C#
To get or set the element at specified index in Collection, the code is as follows −
Example
using System;
using System.Collections.ObjectModel;
public class Demo {
public static void Main() {
Collection<string> col = new Collection<string>();
col.Add("Laptop");
col.Add("Desktop");
col.Add("Notebook");
col.Add("Ultrabook");
col.Add("Tablet");
col.Add("Headphone");
col.Add("Speaker");
Console.WriteLine("Elements in Collection...");
foreach(string str in col) {
Console.WriteLine(str);
}
Console.WriteLine("Element at index 3 = " + col[3]);
Console.WriteLine("Element at index 4 = " + col[4]);
}
}
Output
This will produce the following output −
Elements in Collection... Laptop Desktop Notebook Ultrabook Tablet Headphone Speaker Element at index 3 = Ultrabook Element at index 4 = Tablet
Example
Let us see another example −
using System;
using System.Collections.ObjectModel;
public class Demo {
public static void Main() {
Collection<string> col = new Collection<string>();
col.Add("Laptop");
col.Add("Desktop");
col.Add("Notebook");
col.Add("Ultrabook");
col.Add("Tablet");
col.Add("Headphone");
col.Add("Speaker");
Console.WriteLine("Elements in Collection...");
foreach(string str in col) {
Console.WriteLine(str);
}
Console.WriteLine("Element at index 3 = " + col[3]);
col[3] = "SSD";
Console.WriteLine("Element at index 3 (Updated) = " + col[3]);
}
}
Output
This will produce the following output −
Elements in Collection... Laptop Desktop Notebook Ultrabook Tablet Headphone Speaker Element at index 3 = Ultrabook Element at index 3 (Updated) = SSD
Advertisements