andres
andres

Reputation: 115

How to get the list index of the nearest number?

How to get the list index where you 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);

Upvotes: 5

Views: 5473

Answers (5)

Pop Catalin
Pop Catalin

Reputation: 62960

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;

Upvotes: 3

Jeff Mercado
Jeff Mercado

Reputation: 134521

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

Upvotes: 1

Guffa
Guffa

Reputation: 700592

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

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

Upvotes: -1

goalie7960
goalie7960

Reputation: 873

If you want the index of the closest number this will do the trick:

int index = list.IndexOf(closest);

Upvotes: 5

David
David

Reputation: 1871

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

Upvotes: -1

Related Questions