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?
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.
var nearest = array. MinBy(x => Math. Abs((long) x - targetNumber));
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];
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)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With