Remove List Elements that appear more than Once In Place

后端 未结 2 1388
梦谈多话
梦谈多话 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() { 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(
            source
                .GroupBy(x => x)
                .Where(x => x.Skip(1).Any())
                .Select(x => x.Key));
    
    source.RemoveAll(n => duplicates.Contains(n));
    

提交回复
热议问题