How to Quickly Remove Items From a List

前端 未结 11 1543
情歌与酒
情歌与酒 2020-11-30 01:45

I am looking for a way to quickly remove items from a C# List. The documentation states that the List.Remove() and List.RemoveAt()<

11条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-30 02:10

    I've found when dealing with large lists, this is often faster. The speed of the Remove and finding the right item in the dictionary to remove, more than makes up for creating the dictionary. A couple things though, the original list has to have unique values, and I don't think the order is guaranteed once you are done.

    List hundredThousandItemsInOrignalList;
    List fiftyThousandItemsToRemove;
    
    // populate lists...
    
    Dictionary originalItems = hundredThousandItemsInOrignalList.ToDictionary(i => i);
    
    foreach (long i in fiftyThousandItemsToRemove)
    {
        originalItems.Remove(i);
    }
    
    List newList = originalItems.Select(i => i.Key).ToList();
    

提交回复
热议问题