How to get the list index where yo开发者_高级运维u can find the closest 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);
If you want the index of the closest number this will do the trick:
int index = list.IndexOf(closest);
You can include the index of each item in an anonymous class and pass it through to the aggregate function, and be available at the end of the query:
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;
Just enumerate over indices and select the index with the smallest delta as you would if you did 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);
Very minor changes to what you already have, since you seem to have the answer already:
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);
The closest number is the one where the difference is the smallest:
int closest = list.OrderBy(n => Math.Abs(number - n)).First();
精彩评论