【问题标题】:Removing items from collection从集合中移除项目
【发布时间】:2014-04-23 15:34:34
【问题描述】:

我有一个 id 列表,具有这些 id 的项目将从集合中删除。

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

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

我怎样才能做到这一点?嵌套循环会起作用,但有更好的方法吗?

【问题讨论】:

  • 要是这是Dictionary<string, itemType>就好了。
  • myitemcollection 类型?
  • @Bharadwaj Collection,其中 MyItem 是一个结构体。

标签: c#


【解决方案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);
}

【讨论】:

  • 他说Remove不存在。
  • 我尝试了您的答案,并在将 Where(返回集合)交换为 First(返回项目)时使其正常工作。 @Bharadway Remove(string id) 不存在,但 Remove(Item item) 存在。
【解决方案2】:

如果 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

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

【讨论】:

    【解决方案3】:

    尝试使用linq

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

    请注意:

    1. 这假定您的 Item 集合具有名为 ID 的数据成员。
    2. 这不是最好的性能...

    【讨论】:

      【解决方案4】:

      如果我正确理解了您的问题,请尝试以下代码片段

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

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

      【讨论】:

        【解决方案5】:

        从理论上讲,您正在处理一个称为闭包的问题。在循环(或 for)中,您应该以各种方式复制您的列表(或数组或您正在迭代的内容)(提及方式不同)伙计们),标记您要删除的那些,然后在循环之外处理它们。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-12-18
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多