ale - 4 months ago 23

C# Question

How to get the closest number from a

`List<int>`

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?

Answer

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)`

.