I was wondering if it is possible to write an expression for a Linq extension (or a custom extension) to filter a collection using a lambda expression that compares two elements of the collection.
In other words, if I have a List<DateTime>
and some value, var v = DateTime.Today
, then I am wondering if it is possible to write create a method that will return the first element of the collection that is less than or equal to the value, current <= v
, with the next element of the collection being greater than or equal to the value, next >= v
.
Please note that the above is just an example, and may or may not be the final implementation.
The following would be a valid solution, were the .First()
method to accept Func<DateTime, DateTime, bool>
with the two DateTime
parameters being consecutive elements of the sequence:
dateCollection.First((current, next) => current <= v && next >= v);
Please also note that with the example given, a valid workaround could be to use .OrderBy
and then find the first index that is greater than d
and subtract 1
. However, this type of comparison is not the only one that I am looking for. I may have a situation in which I am checking a List<string>
for the first situation where the current
element starts with the first letter of my value, v
, and the next
element ends with the last letter of my value, v
.
I am looking for something that would be just a few of code. My goal is to find the simplest solution to this possible, so brevity carries a lot of weight.
What I am looking for is something of the form:
public static T First (...)
{
...
}
I believe that this will also require two or more lambda expressions as parameters. One thing that may also provide a good solution is to be able to select into all possible, consecutive pairs of elements of the sequence, and call the .First()
method on that.
For example:
//value
var v = 5;
//if my collection is the following
List<int> stuff = { a, b, c, d };
//select into consecutive pairs, giving:
var pairs = ... // { { a, b }, { b, c }, { c, d } };
//then run comparison
pairs.First(p => p[0] <= v && p[1] >= v).Select(p => p[0]);
Thanks and happy coding! :)