1

I can find a bunch of different ways of removing duplicates such as LINQ "Distinct().ToList()", but that still leaves the value that had duplicates, but I want to remove all values which have duplicates. If you have a list of "1, 2, 3, 3, 4" I want "1, 2, 4" to be left. Thanks!

ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86
Danny
  • 19
  • 1

2 Answers2

4

If you prefer Linq solution, you can try GroupBy instead of Distinct:

 var result = list
   .GroupBy(item => item)               // group items
   .Where(group => group.Count() == 1)  // keep groups with single item only
   .SelectMany(group => group)          // flatten groups to sequence of items
   .ToList();

If you are looking for in place solution (you want to remove duplicates from existing list):

  HashSet<int> duplicates = new HashSet<int>(list
    .GroupBy(item => item)
    .Where(group => group.Count() > 1)
    .Select(group => group.Key));

  int p = 0;

  for (int i = 0; i < list.Count; ++i) 
    if (!duplicates.Contains(list[i]))
      list[p++] = list[i];

  list.RemoveRange(p, list.Count - p);
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
0

Via GroupBy, you can find all duplicates. With Except, you find all entries that are not duplicates:

List<int> output = input.Except(input.GroupBy(i => i).Where(g => g.Count() > 1).Select(g => g.Key)).ToList();

Online demo: https://dotnetfiddle.net/vTo4Cx

SomeBody
  • 7,515
  • 2
  • 17
  • 33