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

C#LinqListNumbers

C# Problem Overview


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?

C# Solutions


Solution 1 - C#

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

Solution 2 - C#

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();

Solution 3 - C#

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.

Solution 4 - C#

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;

Solution 5 - C#

You could you the binary search. It is the build in method in c# that will help you search for the number closest. Here example: https://msdn.microsoft.com/en-us/library/y15ef976(v=vs.110).aspx

Solution 6 - C#

Use this get nearest lower or Higher based on condition You used.

 List<int> list = new List<int> { 2, 5, 7, 10 };
 int number = 9;
 var closest = list.Where(numbers => numbers > number).First();
 Console.WriteLine(closest);
 Console.ReadLine();

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionaleView Question on Stackoverflow
Solution 1 - C#Elian EbbingView Answer on Stackoverflow
Solution 2 - C#Anthony PegramView Answer on Stackoverflow
Solution 3 - C#Theodore ZographosView Answer on Stackoverflow
Solution 4 - C#LevView Answer on Stackoverflow
Solution 5 - C#A. RandhawaView Answer on Stackoverflow
Solution 6 - C#TAMIL ARASANView Answer on Stackoverflow