Senior
How to remove duplicates from an array? What methods are there?
sobes.tech AI
Answer from AI
In C#, there are several ways to remove duplicates from an array:
- Use LINQ and the
Distinct()method:
int[] array = {1, 2, 2, 3, 4, 4, 5};
var distinctArray = array.Distinct().ToArray();
- Use
HashSet<T>, which automatically stores only unique elements:
int[] array = {1, 2, 2, 3, 4, 4, 5};
var set = new HashSet<int>(array);
int[] distinctArray = set.ToArray();
-
For complex objects, you can implement
IEqualityComparer<T>and use it withDistinct()orHashSet. -
If sorting and removing duplicates is needed, you can sort the array and then iterate through it, selecting unique elements.
LINQ Distinct() is the simplest and most readable way for most cases.