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)
just to extrapolate on the other LINQ solutions this extension method will return -1 if no objects fits the filter and expects that the list is all positive integers
public static int SearchForLimit(this IEnuemerable sequence, Predicate filter)
{
return (from i in sequence
let n = filter(i) ? i : -1
select n).Max()
}
usage would look like this:
int[] arr1 = { 1, 23, 57, 59, 120 };
int limitedBy109 = arr1.SearchForLimit(i => i < 109);