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
How to use Remove, RemoveAt, RemoveRange methods in C# list collections?
To implement Remove() and RemoveAt() methods in C#, try the following code −
Firstly, set a list.
List<string> myList = new List<string>() {
"mammals",
"reptiles",
"amphibians",
"vertebrate"
};
Now, use Remove() method to remove an element.
myList.Remove("reptiles");
Now, use RemoveAt() method to remove an element by setting the position.
myList.RemoveAt(2);
The following is the complete code −
Example
using System;
using System.Collections.Generic;
using System.Linq;
class Program {
static void Main() {
List<string> myList = new List<string>() {
"mammals",
"reptiles",
"amphibians",
"vertebrate"
};
Console.Write("Initial list...");
foreach (string list in myList) {
Console.WriteLine(list);
}
Console.Write("Using Remove() method...");
myList.Remove("reptiles");
foreach (string list in myList) {
Console.WriteLine(list);
}
Console.Write("Using RemoveAt() method...");
myList.RemoveAt(2);
foreach (string list in myList) {
Console.WriteLine(list);
}
}
}
Here is an example that implements RemoveRange() method.
Example
using System;
using System.Collections.Generic;
using System.Linq;
class Program {
static void Main() {
List<int> myList = new List<int>();
myList.Add(5);
myList.Add(10);
myList.Add(15);
myList.Add(20);
myList.Add(25);
myList.Add(30);
myList.Add(35);
Console.Write("Initial list...");
foreach (int list in myList) {
Console.WriteLine(list);
}
Console.Write("New list...");
int rem = Math.Max(0, myList.Count - 3);
myList.RemoveRange(0, rem);
foreach (int list in myList) {
Console.Write("
"+list);
}
}
}Advertisements