xxxxxxxxxx
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
int elementToRemove = 3;
numbers.Remove(elementToRemove);
foreach (int number in numbers)
{
Console.WriteLine(number);
}
xxxxxxxxxx
var resultList = new List<int>();
resultList.Add(1);
resultList.Add(2);
resultList.Add(3);
// Removes the number 1 from the index 0 in the list
resultlist.RemoveAt(0);
// Allows you to remove an Object from the list instead
var itemToRemove = resultlist.Single(r => r.Id == 2);
resultList.Remove(itemToRemove);
xxxxxxxxxx
list.Remove("Example String"); // Remove by value
list.RemoveAt(3); // Remove at index
list.RemoveRange(6, 3); // Remove range (removes 3 items starting at 6th position in this example)
To remove an element from a list in C#, you can use the Remove() method or the RemoveAt() method.
The Remove() method removes the first occurrence of a specified object from the list. For example:
xxxxxxxxxx
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
numbers.Remove(3); // Removes the first occurrence of 3
//The RemoveAt() method removes the element at the specified index. For example:
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
numbers.RemoveAt(3); // Removes the element at index 3 (i.e., the fourth element)
xxxxxxxxxx
// C# program to illustrate how
// to remove objects from the list
using System;
using System.Collections.Generic;
class GFG {
// Main Method
static public void Main()
{
// Creating list using List class
// and List<T>() Constructor
List<int> my_list = new List<int>();
// Adding elements to List
// Using Add() method
my_list.Add(1);
my_list.Add(10);
my_list.Add(100);
my_list.Add(1000);
my_list.Add(10000);
my_list.Add(100000);
my_list.Add(1000000);
my_list.Add(10000000);
my_list.Add(100000000);
// Initial count
Console.WriteLine("Initial count:{0}", my_list.Count);
// After using Remove() method
my_list.Remove(10);
Console.WriteLine("2nd count:{0}", my_list.Count);
// After using RemoveAt() method
my_list.RemoveAt(4);
Console.WriteLine("3rd count:{0}", my_list.Count);
// After using RemoveRange() method
my_list.RemoveRange(0, 2);
Console.WriteLine("4th count:{0}", my_list.Count);
// After using Clear() method
my_list.Clear();
Console.WriteLine("5th count:{0}", my_list.Count);
}
}