Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the list index of the nearest number?

Tags:

c#

.net

linq

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);
like image 772
andres Avatar asked May 10 '11 22:05

andres


People also ask

How do you find the nearest value in a list?

We can find the nearest value in the list by using the min() function. Define a function that calculates the difference between a value in the list and the given value and returns the absolute value of the result. Then call the min() function which returns the closest value to the given value.

How do you find the index of the closest value in an array in Python?

Use numpy. argmin(), to obtain the index of the smallest element in difference_array[]. In the case of multiple minimum values, the first occurrence will be returned. Print the nearest element, and its index from the given array.

How do you find the index of a string in a list?

By using type() operator we can get the string elements indexes from the list, string elements will come under str() type, so we iterate through the entire list with for loop and return the index which is of type string.

How do you find the index of an integer in a list?

To find index of the first occurrence of an element in a given Python List, you can use index() method of List class with the element passed as argument. The index() method returns an integer that represents the index of first match of specified element in the List.


2 Answers

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

int index = list.IndexOf(closest);
like image 156
goalie7960 Avatar answered Oct 26 '22 21:10

goalie7960


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;
like image 45
Pop Catalin Avatar answered Oct 26 '22 21:10

Pop Catalin