DEV Community

Andre Carstens
Andre Carstens

Posted on • Edited on

C# arrays using Distinct

int[] nums = new int[] { 1, 4, 5, 2, 3, 5, 6 };
//unique values
var unique = nums.Distinct();
Enter fullscreen mode Exit fullscreen mode

There is a array of integers as an example above. The Distinct() command will shorten the integer array by removing any duplicate values and returning a shortened array. The duplicate value (5) will be removed and the resulting array will be {1, 4, 2, 3, 5, 6}

Note: The array will not be sorted yet, only the duplicate values removed. To sort the array, you can chain a call to OrderBy() at the end of Distinct().

Question:
Can you specify which values in an integer array, you want to apply Distinct to?

var selectedDistinct = nums.Where(x => x >= 3).Select(x => x).Distinct();

Enter fullscreen mode Exit fullscreen mode

The code above will shorten nums to only values that are greater or equal to 3 and then apply Distinct() to that shortened result.

Top comments (0)