简体   繁体   中英

Delete an item from a C# collections List object

In my C# project , I am using a Hashtable , but it is not able to store more than one value with same key. So I changed it to use List . I am getting data from sql and loading the List . After loading data I want to remove items from list based on an id. How can I make it possible?

You could use the List<T>.RemoveAll method, which takes a Predicate<T> as an argument.

For example, if you wanted to remove all items with an Id of 5 , you could do:

int numRemoved = list.RemoveAll(x => x.Id == 5);

You could try linq on your List<T> .

yourList.RemoveAll(item => item.Id == yourKey);

Assuming you are storing items that have a field to compare against.

MSDN link for reference to RemoveAll :

http://msdn.microsoft.com/en-us/library/wdka673a.aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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