C
C#2y ago
Natty

Clean up LINQ statements?

var cashFlowDates = db.CashFlows.Include(cash => cash.Cells).OrderByDescending(cash => cash.Id).FirstOrDefault().Cells.Where(cell => cell.Column == 0).Select(cell => cell.Value).Distinct();
var balanceDates = db.Balances.Include(bal => bal.Cells).OrderByDescending(bal => bal.Id).FirstOrDefault().Cells.Where(cell => cell.Column == 0).Select(cell => cell.Value).Distinct();
var performanceDates = db.Benchmarks.Include(bench => bench.Cells).OrderByDescending(bench => bench.Id).FirstOrDefault().Cells.Where(cell => cell.Column == 0).Select(cell => cell.Value).Distinct();
var allDates = cashFlowDates.Concat(balanceDates).Concat(performanceDates).Distinct();
var cashFlowDates = db.CashFlows.Include(cash => cash.Cells).OrderByDescending(cash => cash.Id).FirstOrDefault().Cells.Where(cell => cell.Column == 0).Select(cell => cell.Value).Distinct();
var balanceDates = db.Balances.Include(bal => bal.Cells).OrderByDescending(bal => bal.Id).FirstOrDefault().Cells.Where(cell => cell.Column == 0).Select(cell => cell.Value).Distinct();
var performanceDates = db.Benchmarks.Include(bench => bench.Cells).OrderByDescending(bench => bench.Id).FirstOrDefault().Cells.Where(cell => cell.Column == 0).Select(cell => cell.Value).Distinct();
var allDates = cashFlowDates.Concat(balanceDates).Concat(performanceDates).Distinct();
In an ideal situation I would just do the query on the Cells table, but that table gets updated with ALL the cells, each time a user uploads a file, and there wouldn't be a way to track which data they want to use then (couldn't remove the old data if it was wrong, etc). What I have here works great, but is there a way to clean up these queries? I.E. Anyway to shorten this? Do I need all the calls here? Does calling Distinct() on each query even make sense (is that slower/faster)? etc.
3 Replies
TheBoxyBear
TheBoxyBear2y ago
If there's a common base class or interface for CashFlow, Balance and Benchmark, you can make method that returns the query from a DbSet of that base type
Natty
NattyOP2y ago
There actually is... hm i didn't think of that.
TheBoxyBear
TheBoxyBear2y ago
More precisely a generic method with the base type as a constraint so you can return set of the exact type needed by the caller If not, have some delegates as parameters to fill the gaps
Want results from more Discord servers?
Add your server