A 'Between' extension method for Linq in C#.
April 2, 2011
Here's an example of a simple Linq extension method for getting values that fall within a certain range from an IEnumerable collection. First, we order the TSource items using the given selector. Then we use Invoke on each item in the collection to determine if the selector's result is above the lowest value we want. If it isn't, we skip it with the SkipWhile method. Once we're at a point where we know the selector's result is at least as large as the lowest value we want, we start taking items with the TakeWhile method until the same Invoke returns a value larger than the largest item we want. Then we just stop and return. It's a one-liner.

1 comment for 'A 'Between' extension method for Linq in C#.'
1. And a quick SQL Server
And a quick SQL Server example:
SELECT *
FROM Persons
WHERE PersonId BETWEEN 40 and 45
Which will give you all persons with an ID between 40 and 45, inclusive.
Post new comment