简体   繁体   中英

Removing items from collection

I have a list of ids, and the items with these ids shall be removed from a Collection.

foreach(string id in list) {
    myitemcollection.Remove(id); // This does not exist. How would I implement it?
}

Unfortunately, "Remove" takes a complete item, which I don't have, and "RemoveAt" takes an index, which I don't have either.

How can I achieve this? Nested loops will work, but is there a better way?

Try using linq :

 var newCollection = myitemcollection.Where(x=> !list.Contains(x.ID));

Please note that:

  1. This assumes that your Item collection has data member called ID .
  2. This is not the best performance wise...

If mycollection is also a list of ints, you could use

List<int> list = new List<int> {1,2,3};
List<int> myitemcollection = new List<int> {1,2,3,4,5,6};
myitemcollection.RemoveAll(list.Contains);

If it is a custom class, lets say

public class myclass
{
    public int ID;
}

you could use

List<int> list = new List<int> {1,2,3};
List<myclass> myitemcollection = new List<myclass>
{
    new myclass { ID = 1},
    new myclass { ID = 2},
    new myclass { ID = 3},
    new myclass { ID = 4},
    new myclass { ID = 5},
    new myclass { ID = 6},
};

myitemcollection.RemoveAll(i => list.Contains(i.ID));

List.RemoveAll Method

Removes all the elements that match the conditions defined by the specified predicate.

One way would be to use linq :

foreach(string id in list) {
    //get item which matches the id
    var item = myitemcollection.Where(x => x.id == id);
    //remove that item
    myitemcollection.Remove(item);
}

If I understood your question rightly, try the below code snip

foreach (string id in list)
{
    if (id == "") // check some condition to skip all other items in list
    {
        myitemcollection.Remove(id); // This does not exist. How would I implement it?
    }
}

If this is not good enough. Make your question more clear to get exact answer

从理论上讲,您正在处理一个叫做闭包的问题。在一个循环中(或用于),您应该以各种方式复制列表(或数组或您要迭代的内容)(这在伙计中有所不同) ,标记您要删除的内容,然后进行循环处理。

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