user3872666 user3872666 - 1 year ago 93
C# Question

C# Find all values in an array closest to a given number


int[] myArray = new int[]{-8, -17, 12, 8, 16, -3, 7, 3};

Find all values in array closest to 0.

Currently using another code found on the site but it only tells me 1 value.

int nearest = myArray.Select(p => new {Value = p, Difference = Math.Abs(p - searchValue)}).OrderBy(p => p.Difference).First().Value;

In the current case both -3 and 3 are closest to 0 but since -3 comes first it only outputs -3.

Is there another way to do this where it finds all values instead of just First()?

Answer Source

Use a grouping on the lowest absolute value

int[] result = myArray
    .OrderBy(i => Math.Abs(i - searchValue))
    .GroupBy(i => Math.Abs(i - searchValue))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download