簡體   English   中英

從集合中刪除項目

[英]Removing items from collection

我有一個ID列表,帶有這些ID的項目將從集合中刪除。

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

不幸的是,“刪除”獲取一個我沒有的完整項目,而“ RemoveAt”獲取一個我沒有的完整索引。

我該如何實現? 嵌套循環可以工作,但是有更好的方法嗎?

嘗試使用linq

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

請注意:

  1. 假設您的Item集合具有名為ID數據成員。
  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方法

刪除所有與指定謂詞定義的條件匹配的元素。

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

如果我正確理解了您的問題,請嘗試以下代碼片段

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

如果這還不夠好。 讓您的問題更清楚以獲得確切答案

從理論上講,您正在處理一個叫做閉包的問題。在一個循環中(或用於),您應該以各種方式復制列表(或數組或您要迭代的內容)(這在伙計中有所不同) ,標記您要刪除的內容,然后進行循環處理。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM