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)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

AWS Security LIVE!

Hosted by security experts, AWS Security LIVE! showcases AWS Partners tackling real-world security challenges. Join live and get your security questions answered.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️