How to get the index of the list of the nearest number?

How to get the list index, where you can find the nearest number?

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); 
+4
source share
5 answers

If you want the closest number index to do the trick:

 int index = list.IndexOf(closest); 
+6
source

You can include the index of each element in an anonymous class and pass it to the aggregate function and be available at the end of the request:

 var closest = list .Select( (x, index) => new {Item = x, Index = index}) // Save the item index and item in an anonymous class .Aggregate((x,y) => Math.Abs(x.Item-number) < Math.Abs(y.Item-number) ? x : y); var index = closest.Index; 
+3
source

Very minor changes to what you already have, since you already have the answer:

  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); 
0
source

The closest number is the one where the difference is the smallest:

 int closest = list.OrderBy(n => Math.Abs(number - n)).First(); 
0
source

Just list the indexes and select the index with the smallest delta, as if you were doing a regular loop.

 const int value = 9; var list = new List<int> { 2, 5, 7, 10 }; var minIndex = Enumerable.Range(1, list.Count - 1) .Aggregate(0, (seed, index) => Math.Abs(list[index] - value) < Math.Abs(list[seed] - value) ? index : seed); 
0
source

All Articles