I have a list of numbers ordered ascending. Given a value I need to know up to what number of the array and its index corresponds.
List<string> myLista = new List<string>(new[] { "2", "9", "17", "25", "35", "42", "70" });
Being the initial index = 0. For a value = 5, the index would be 1 and the number 9 For a value = 17, the index would be 2 and the number 17 For a value = 0, the index would be 0 and the number 2
This is a possible approximation but I am only interested in knowing the index and value of the last element of the list:
myLista.Where(x => Int32.Parse(x) <= Int32.Parse("31")).ToList()
If I understand you correctly, you need the index of the last number in the list that is less than or equal to the value you are checking. This method will give you:
Once you have the index, you can easily retrieve the value with
valores[indice]
.I see that in Konamiman's answer you ask for a solution in Linq. The only thing I can think of is the following:
We can use the overload of
Select<TSource,TResult>(IEnumerable<TSource>, Func<TSource,Int32,TResult>)
which incorporates the index of the elements, to create a result using a new anonymous class that returns both the value and the index within the list.This is an example that I think does what you ask for:
As you can see, we first use
Select
it to create a class that has the propertiesValor
eIndice
. Subsequently, we search for the elements that are greater than or equal to the searched element, and we keep the first one.Keep in mind that if the value passed to it is greater than the largest value in the list, the result in
listaConIndices
would benull
, so we should check it later.