Distinct elements from an array in C#
To get distinct elements from an array in C# you can useDistinct()
from Linq namespace which returns distinct elements from a sequence, and then use the method ToArray()
.Example
using System;
using System.Linq;
public class Program
{
public static void Main()
{
int[] arr = { 1, 2, 3, 3};
arr = arr.Distinct().ToArray();
Console.WriteLine(arr[0]);
Console.WriteLine(arr[1]);
Console.WriteLine(arr[2]);
Console.WriteLine("Array size: " + arr.Count());
}
}
Output
1
2
3
Array size: 3
2
3
Array size: 3