I have a table that has the result of some conversions and i need to join the converted values with all the actual values in my backend using a approximate filter.
I could do it with a query like this:
with values_to_search as (
select 13 as quantity
union
select 21 as quantity
union
select 30 as quantity
)
select
vts.quantity,
converted.ConvertedQuantityMg
from values_to_search vts
OUTER APPLY (
select top 1
cd.ConvertedQuantityMg
from MyConversion cd
where
cd.Quantity <= vts.quantity
order by cd.Quantity desc
) as converted
Obs: The values_to_search
cte is just to simulate the data that are going to be queried.
The only solution I could think of, doing it in a single query, is to get all data in memory filtering by range and getting the exact converted value in memory.
Something like:
var valuesToFilter = new List<int>() { 13, 21, 30 };
var results = _context.Set<MyConversion>()
.Where(conversion => conversion.Quantity >= valuesToFilter.Min() &&
conversion.Quantity <= valuesToFilter.Max())
.ToList();
foreach (var val in valuesToFilter )
{
var convertedValue = results.Where(conversion => conversion.Quantity <= val)
.OrderByDescending(conversion => conversion.Quantity)
.FirstOrDefault();
}
There's a way to translate the above sql query to Linq? I'm using EF Core 2.6.