Sobes.tech
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:

  1. Use LINQ and the Distinct() method:
int[] array = {1, 2, 2, 3, 4, 4, 5};
var distinctArray = array.Distinct().ToArray();
  1. 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();
  1. For complex objects, you can implement IEqualityComparer<T> and use it with Distinct() or HashSet.

  2. 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.