LinQ maximum date in a single query

entity-framework linq linq-to-entities

Question

I own the next 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;

However, I've been looking for methods to optimize it by using one query rather than one. Any suggestions?

1
9
11/2/2010 3:40:28 PM

Accepted Answer

Use OrderByDescending Then choose the first file:

initialBalance = ctx.DailyBalances
   .OrderByDescending(c => c.DailyDate)
   .Select(c => c.FinalBalance)
   .FirstOrDefault();

SQL Server has been tuned for this kind of query so that the full table does not need to be sorted in O(n log(n)). If an index is availableDailyDate Without an index, it will utilize an efficient method called Top N Sort that executes in linear time to locate the final row in the index.

In LINQ to Objects, this query will be O(n log(n)) nonetheless.

18
11/2/2010 4:07:19 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow