Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the closest number from a List<int> with LINQ?

How to get the closest number from a List<int> with LINQ?

For example:

List<int> numbers = new List<int>(); numbers.Add(2); numbers.Add(5); numbers.Add(7); numbers.Add(10) 

I need to find the closest value in the list to number 9. In this case 10.

How can I do this with LINQ?

like image 232
ale Avatar asked May 10 '11 16:05

ale


People also ask

How do you find the nearest value in a list?

We can find the nearest value in the list by using the min() function. Define a function that calculates the difference between a value in the list and the given value and returns the absolute value of the result. Then call the min() function which returns the closest value to the given value.

How do I find the nearest number in C#?

var nearest = array. MinBy(x => Math. Abs((long) x - targetNumber));

How do you find the nearest number to a number in Java?

abs(numbers[0] - myNumber); int idx = 0; for(int c = 1; c < numbers. length; c++){ int cdistance = Math. abs(numbers[c] - myNumber); if(cdistance < distance){ idx = c; distance = cdistance; } } int theNumber = numbers[idx];


1 Answers

If you use LINQ to Objects and the list is long, I would use:

List<int> list = new List<int> { 2, 5, 7, 10 }; int number = 9;  int closest = list.Aggregate((x,y) => Math.Abs(x-number) < Math.Abs(y-number) ? x : y); 

This method is slightly more complex than the solution that Anthony Pegram suggested, but it has as advantage that you don't have to sort the list first. This means that you have a time complexity of O(n) instead of O(n*log(n)) and a memory usage of O(1) instead of O(n).

like image 72
Elian Ebbing Avatar answered Oct 15 '22 12:10

Elian Ebbing