How to get the closest number from a List<int> with LINQ?
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 want to use LINQ to perform this task, you can do it like below.
List<int> list = new List<int> { 2, 5, 7, 10 };
int number = 9;
// find closest to number
int closest = list.OrderBy(item => Math.Abs(number - item)).First();
The solutions above are all O(N)
at best.
If you have a big list and you perform this closest-element query multiple times, it would be more performant to sort the list first ( O(NlogN)
) and then use List<T>.BinarySearch
for each query. The performance for k
queries is O( (k+N)logN )
, in comparison to O(kN)
of the previous method.
These days there also exist a nice and simple option:
List<int> list = new List<int> { 2, 5, 7, 10 };
int number = 9;
int min = list.Min(i => (Math.Abs(number - i), i)).i;