I need a linq expression that will find the nearest numbers (both ‘greater or equal’ and ‘less or equal’) in an array for a given number.
E.g. Array – 1, 33, 66, 100
If I have the number 10, I want to return 1 and 33. If I have the number 70, I want to return 66 and 100. If I have the number 33, I want to return 33 and 66.
I could do this with some kind of basic for loop, but this is an operation on numbers in a database, so I’d prefer a linq to sql expression.
Edit: I was actually searching for a single linq expression to achieve this, but perhaps I was being a little hopeful 🙂
Similar to Andrews answer, but I prefer doing the filter before the OrderBy, which reduces the amount of data the query has to run through. Also OrderBy.First is the same as Min, and OrderByDescending.First is the same as Max.