Try using List.BinarySearch.
Returns the zero-based index of item in the sorted List, if item is found; otherwise, a negative number that is the bitwise complement of the index of the next element that is larger than item or, if there is no larger element, the bitwise complement of Count.
var list = new List<int> { 16, 25, 35, 50, 70, 95, 120, 150, 185, 240, 300, 400 };
int index = list.BinarySearch(result);
int rounded;
if (index < 0)
{
if (~index == list.Count)
{
throw new InvalidOperationException("Number is too big.");
}
rounded = list[~index];
}
else
{
rounded = list[index];
}
The asymptotic complexity of this method is O(log n)
, where n
is the length of the list, whereas the complexity of Where
/First
is O(n)
, which probably won't matter in your case, but is still good to know.