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!
Asked
Active
Viewed 303 times
1
-
Must the duplicates be removed from the original list, or is a new list with the duplicates removed acceptible? – Matthew Watson Mar 22 '21 at 10:14
2 Answers
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
-
@JohnathanBarclay The OP wanted to _remove_ duplicates. Distinct doesnt do that – Jamiec Mar 22 '21 at 10:08
-
-
1Another option: `list.ToLookup(i => i).Where(x => x.Count() == 1).Select(x => x.Key)` – Tim Schmelter Mar 22 '21 at 10:20
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