Suppose I have a sorted array of integers int[]
, and I want to search the closest smaller value to some input number.
for example if the array contains (1)
using Linq:
int[] arr = new[] { 1, 23, 57, 59, 120 };
int target = 109;
int max = arr.Where(n => n < target).Max();
Maybe not the fastest but probably the easiest to implement. Also doesn't rely on the array being sorted, as binary search does.
Note that the call to Max
will throw an exception if the Where
filter results in no elements, so you might want to check that if it's a possibility.