I have the following code:
Decimal initialBalance;
DateTime dailyDate = ctx.DailyBalances.Max(c => c.DailyDate);
if (dailyDate != null)
initialBalance = ctx.DailyBalances.Where(c => c.DailyDate == dailyDate).Select(c => c.FinalBalance).FirstOrDefault();
else
initialBalance = 0;
return initialBalance;
Nevertheless i’ve been trying to get ways to optimized it,making one query instead of one… any sugestion??
Use
OrderByDescendingand take the first record:This type of query is optimized in SQL Server so that it doesn’t require an O(n log(n)) sort of the entire table. If there is an index on
DailyDateit will find the last row in the index, and without an index it will use an optimized algorithm calledTop N Sortthat runs in linear time.However this query will be O(n log(n)) in LINQ to Objects.