Remove List Elements that appear more than Once In Place

后端 未结 2 1387
梦谈多话
梦谈多话 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:45

    So, if you can have a new list, then this is the easiest way to do it:

    var source = new List<int>() { 4, 5, 7, 3, 5, 4, 2, 4 };
    
    var result =
        source
            .GroupBy(x => x)
            .Where(x => !x.Skip(1).Any())
            .Select(x => x.Key)
            .ToList();
    

    This gives:

    { 7, 3, 2 }
    

    If you want to remove the values from the original source, then do this:

    var duplicates =
        new HashSet<int>(
            source
                .GroupBy(x => x)
                .Where(x => x.Skip(1).Any())
                .Select(x => x.Key));
    
    source.RemoveAll(n => duplicates.Contains(n));
    
    0 讨论(0)
  • 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<int> hash = new HashSet<int>();
    
    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

    0 讨论(0)
提交回复
热议问题