Remove List Elements that appear more than Once In Place

后端 未结 2 1386
梦谈多话
梦谈多话 2021-01-24 14:33

There is a similar question posted, but I do not have the rep to ask a follow-up question in that thread :(

That question and solution is HERE.

If I have a Lis

2条回答
  •  鱼传尺愫
    2021-01-24 14:50

    I have two options for you, one that uses HashSet and other Linq .

    Option 1:

    Using HashSet, loop through collection and insert if it not exist and remove if it exists.

    HashSet hash = new HashSet();
    
    foreach(var number in list)
    {
        if(!hash.Contains(number)) hash.Add(number);
        else hash.Remove(number);               
    }
    list = hash.ToList();
    

    Option 2:

    Simple Linq, group the elements and filter whose count >1.

    var list= list.GroupBy(g=>g)
        .Where(e=>e.Count()==1)
        .Select(g=>g.Key)
        .ToList();
    

    There is big performance gain using HashSet over Linq, it is obvious, Linq(in this case) require multiple iterations, where as HashSet uses single iteration and provides LookUp (for adding/removing) with O(1) access.

    Elapsed Time (Using Linq): 8808 Ticks
    Elapsed Time (Using HashSet): 51 Ticks
    

    Working Demo

提交回复
热议问题