Alexander
Alexander

Reputation: 20224

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?

Upvotes: 0

Views: 83

Answers (5)

Ali Dehghan
Ali Dehghan

Reputation: 462

In terms of theory, you are dealing with a matter called closure.Within a loop (or for), you should make a copy of your list (or array or what you are iterating) in every way (that is mentioned differently by guys), mark those you want to remove and then deal with them out of the loop.

Upvotes: 0

Avi Turner
Avi Turner

Reputation: 10456

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...

Upvotes: 1

UvarajGopu
UvarajGopu

Reputation: 27

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

Upvotes: 0

James
James

Reputation: 2201

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);
}

Upvotes: 1

Adriaan Stander
Adriaan Stander

Reputation: 166396

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.

Upvotes: 1

Related Questions