EN
C# / .NET - remove items from List
0
points
In this article, we would like to show you how to remove items from List in C#.
Quick solution:
List<string> myList = new List<string> { "A", "B", "C", "A" };
myList.Remove("A");
myList.ForEach(x => Console.WriteLine(x)); // Output: B,C,A
or:
List<string> myList = new List<string> { "A", "B", "C", "A" };
myList.RemoveAt(0);
myList.ForEach(x => Console.WriteLine(x)); // Output: B,C,A
1. Practical example using Remove() method
In this example, we use Remove() method to remove item from myList by value.
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
List<string> myList = new List<string> { "A", "B", "C", "A" };
myList.Remove("A");
foreach (string item in myList)
Console.WriteLine(item);
}
}
Output:
B
C
A
2. Remove item at index
In this example, we use RemoveAt() method to remove item at specific index from myList().
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
List<string> myList = new List<string> { "A", "B", "C", "A" };
myList.RemoveAt(0);
foreach (string item in myList)
Console.WriteLine(item);
}
}
Output:
B
C
A