Remove duplicates from a List in C#

前端 未结 27 1765
广开言路
广开言路 2020-11-22 04:41

Anyone have a quick method for de-duplicating a generic List in C#?

27条回答
  •  终归单人心
    2020-11-22 05:25

    As kronoz said in .Net 3.5 you can use Distinct().

    In .Net 2 you could mimic it:

    public IEnumerable DedupCollection (IEnumerable input) 
    {
        var passedValues = new HashSet();
    
        // Relatively simple dupe check alg used as example
        foreach(T item in input)
            if(passedValues.Add(item)) // True if item is new
                yield return item;
    }
    

    This could be used to dedupe any collection and will return the values in the original order.

    It's normally much quicker to filter a collection (as both Distinct() and this sample does) than it would be to remove items from it.

提交回复
热议问题