简体   繁体   English

根据ASP.NET中的值删除列表中的项目

[英]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 ? 如何不使用productsAll.RemoveAt删除productsAll的项目?

I can't delete the value based on index, as productsAll will be heavily modified with each interactions in the page. 我无法基于索引删除该值,因为productsAll将随着页面中的每次交互而大量修改。

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 点击msdn链接以获取更多说明

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

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. Remove是从列表中删除特定项目的好方法,如果要删除多个元素,则也可以尝试使用RemoveAll 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: 您也可以尝试使用.Contains()通过使用以下代码来删除包含特定文本的项目:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM