Languages
[Edit]
EN

C# / .NET - remove items from List

0 points
Created by:
Elleanor-Williamson
380

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

References

  1. List<T>.Remove(T) Method (System.Collections.Generic) | Microsoft Docs
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join