簡體   English   中英

從有序集合中刪除項目的最佳方法是什么?

[英]What's the best way to remove items from an ordered collection?

我有要從C#中的有序列集合中刪除的項目列表。

最好的方法是什么?

如果我在中間刪除一個項目,索引會改變,但是如果我想刪除多個項目該怎么辦?

為了避免索引更改,請從末尾開始,然后返回索引0。

遵循以下原則:

for(int i = myList.Count - 1; i >= 0; i++) 
{
    if(NeedToDelete(myList[i]))
    {
        myList.RemoveAt(i);
    }
}

收藏的類型是什么? 如果它繼承自ICollection ,則可以對要刪除的項目列表進行循環,然后在集合上調用.Remove()方法。

例如:

object[] itemsToDelete = GetObjectsToDeleteFromSomewhere();
ICollection<object> orderedCollection = GetCollectionFromSomewhere();

foreach (object item in itemsToDelete)
{
    orderedCollection.Remove(item);
}

如果集合是List<T> ,則還可以使用RemoveAll方法:

list.RemoveAll(x => otherlist.Contains(x));

假設要刪除的項目列表相對較短,則可以首先對目標列表進行排序。 比遍歷源列表並在目標列表中保留一個與您刪除的項目相對應的索引。

假設源列表是haystack ,要刪除的項目列表是needle

needle.Sort(); // not needed if it's known that `needle` is sorted
// haystack is known to be sorted
haystackIdx = 0;
needleIdx = 0;
while (needleIdx < needle.Count && haystackIdx < haystack.Count)
{
    if (haystack[haystackIdx] < needle[needleIdx])
        haystackIdx++;
    else if (haystack[haystackIdx] > needle[needleIdx])
        needleIdx++;
    else
        haystack.RemoveAt(haystackIdx);
}

這樣,您只需要遍歷haystackneedle 1個遍歷,再加上對needle進行排序的時間,前提是刪除值為O(1) (對於鏈表和類似的集合通常是這種情況)。 如果集合是List<...> ,則由於數據移位,刪除將需要O(collection size) ,因此最好從兩個集合的末尾開始,然后移至開始:

needle.Sort(); // not needed if it's known that `needle` is sorted
// haystack is known to be sorted
haystackIdx = haystack.Count - 1;
needleIdx = needle.Count - 1;
while (needleIdx >= 0 && haystackIdx >= 0)
{
    if (haystack[haystackIdx] > needle[needleIdx])
        haystackIdx--;
    else if (haystack[haystackIdx] < needle[needleIdx])
        needleIdx--;
    else
        haystack.RemoveAt(haystackIdx--);
}

暫無
暫無

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

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