从集合中删除项目

时间:2014-04-23 07:22:06

标签: c#

我有一个id列表,带有这些id的项目将从Collection中删除。

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

不幸的是,“删除”需要一个完整的项目,我没有,“RemoveAt”采用索引,我也没有。

我怎样才能做到这一点?嵌套循环可以工作,但是有更好的方法吗?

5 个答案:

答案 0 :(得分:1)

尝试使用linq

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

请注意:

  1. 这假设您的Item集合中包含名为ID的数据成员。
  2. 这不是最好的表现......

答案 1 :(得分:1)

如果mycollection也是一个整数列表,你可以使用

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

如果是自定义类,请说

public class myclass
{
    public int ID;
}

你可以使用

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

  

删除符合条件定义的所有元素   指定的谓词。

答案 2 :(得分:1)

一种方法是使用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);
}

答案 3 :(得分:0)

如果我理解你的问题,请尝试以下代码片段

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?
    }
}

如果这还不够好。让您的问题更加清晰,以获得确切的答案

答案 4 :(得分:0)

就理论而言,你正在处理一个叫做闭包的问题。在一个循环(或for)中,你应该以各种方式复制你的列表(或数组或你正在迭代的东西)(不同地提到)由人员),标记你想要删除的那些,然后在循环中处理它们。

相关问题