Remove duplicates from a List in C#

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

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

27条回答
  •  春和景丽
    2020-11-22 05:13

    If you don't care about the order you can just shove the items into a HashSet, if you do want to maintain the order you can do something like this:

    var unique = new List();
    var hs = new HashSet();
    foreach (T t in list)
        if (hs.Add(t))
            unique.Add(t);
    

    Or the Linq way:

    var hs = new HashSet();
    list.All( x =>  hs.Add(x) );
    

    Edit: The HashSet method is O(N) time and O(N) space while sorting and then making unique (as suggested by @lassevk and others) is O(N*lgN) time and O(1) space so it's not so clear to me (as it was at first glance) that the sorting way is inferior (my apologies for the temporary down vote...)

提交回复
热议问题