If you are working with C# List, then it is possible that you may want to add or remove item from a list, so in this article, I have mentioned how we can remove an item from C# list with console application example.
There are two methods to remove item from List
- RemoveAt(Item_Position): The RemoveAt() method removes the first occurrence of a specific object from a List, where item_position = index of the item which we want to remove.
- RemoveRange(int index, int count): This method will remove multiple items begining from index, or you can say removes a number of items based on the specified starting index and the number of items. So, if you want to remove 3 items from a list starting from 2nd position, then it would be as
ExampleList.RemoveRange(2,3);
- Remove(Item): You can also remove item from list using Remove(Item) method, where item = one of the list items.
Let's take a look at console application example, where we will first add items in list and then we will delete it.
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
//create list of name
List<string> names = new List<string>();
// add items
names.Add("Suresh");
names.Add("Vikram");
names.Add("Vikas");
names.Add("Harish");
Console.WriteLine("Names before removing item");
foreach(var name in names)
{
Console.WriteLine(name);
}
Console.WriteLine("-----------");
//remove item at index =2 ("Vikas")
names.RemoveAt(2);
Console.WriteLine("Names after removing item at position 2");
foreach(var name in names)
{
Console.WriteLine(name);
}
Console.WriteLine("-----------");
//remove 2 items starting from index position 1
names.RemoveRange(1,2);
Console.WriteLine("Names after removing 2 items starting from index position 1");
foreach(var name in names)
{
Console.WriteLine(name);
}
}
}
Output:
Names before removing item
Suresh
Vikram
Vikas
Harish
-----------
Names after removing item at position 2
Suresh
Vikram
Harish
-----------
Names after removing 2 items starting from index position 1
Suresh
You may also like to read:
SingleOrDefault vs FirstOrDefault in C#
Create or initialize List Tuple in C#
Return Multiple values in C# (Various ways)
Add values in C# array (Multiple ways)
Find Element based on Data-Attribute using Javascript or jQuery