Kerzoz
Kerzoz

Reputation: 331

Delete items in a list based on its value in ASP.NET

I have a list of string:

List<string> productsAll = new List<string>();
productsAll.Add("CMT_40");
productsAll.Add("CMT_50");
productsAll.Add("Mortar");

How do I remove the items at productsAll without using productsAll.RemoveAt?

I can't delete the value based on index, as productsAll will be heavily modified with each interactions in the page.

Upvotes: 0

Views: 88

Answers (2)

sujith karivelil
sujith karivelil

Reputation: 29026

Remove is a nice option to remove a specific item from the list, if you want to remove more than one elements means you can try RemoveAll as well. you can try the following code:

List<string> productsAll = new List<string>();
productsAll.Add("CMT_40");
productsAll.Add("CMT_50");
productsAll.Add("Mortar");
productsAll.Add("Mortar");
productsAll.Add("Mortar");
string itemToRemove = "Mortar";

productsAll.RemoveAll(x=>x==itemToRemove);  

Check this Example for working demo. You can also try removing items that contains specific text by using .Contains() by using the following code:

 productsAll.RemoveAll(x=>x.Contains(itemToRemove));    

Upvotes: 0

devil_coder
devil_coder

Reputation: 1135

You can just remove item from the list if you know the item you would like to delete

Use

productsAll.Remove("item123");

Follow msdn link for more explanation

https://msdn.microsoft.com/en-us/library/cd666k3e.aspx

Upvotes: 2

Related Questions