This is hard to explain. I wanted to get all of the items in collection one (ints in the example below) that are the highest values that are lower than any of the items in collection two (otherInts). In the example below, only 2 and 8 should be returned from ints. 1 doesn't qualify because it is lower than 3 (in otherInts), but 2 is higher than 1, but still lower than 3. 2 does qualify because there is nothing higher than it that is lower than 3. 5 does not qualify for the same reason as 1, namely, 8 is higher than it, but also lower than 9 (in otherInts).
I've written the following linq to accomplish this. I'd like to stay constrained to linq as opposed to a standard forEach since this is a sub-linq statement. Is there a better linq way to accomplish this?
var ints = new List<int>{1,2,5,8};
var otherInts = new List<int>{3,4,9};
var intsImmediatelyLessThanOrEqualToOtherInts = from i in ints
let firstGreaterOtherInt = otherInts.First(o => o > i)
let intBetweenThisAndOther = from i2 in ints
where i2 > i && i2 < firstGreaterOtherInt
select i2
select intBetweenThisAndOther.Count() > 0 ? null as object : i;
intsImmediatelyLessThanOrEqualToOtherInts.Where(i => i != null).ToList().ForEach(Console.WriteLine);
Here's a working fiddle if you want to test other cases.