Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq (MIN && MAX)

Tags:

linq

What is equal of below sql in LINQ

select MIN(finishTimestamp) AS FromDate, MAX(finishTimeStamp) AS ToDate From Transactions

??

from t in Transactions
select new {
          FromDate = ?,
          ToDate = ?
        }

Thanks

like image 268
Sreedhar Avatar asked Jul 10 '09 05:07

Sreedhar


2 Answers

To use multiple aggregates in Linq to SQL, on a table, without grouping, the only way I've found to avoid doing multiple queries, is to make a "fake group":

 var q = from tr in dataContext.Transactions
         group tr by 1 into g // Notice here, grouping by a constant value
         select new
         {
           FromDate = g.Min(t => t.InvoiceDate),
           ToDate = g.Max(t => t.InvoiceDate)
         };

Kinda hacky, but the generated SQL is clean, and by doing so, you make only one query to the database.

like image 71
Christian C. Salvadó Avatar answered Sep 26 '22 08:09

Christian C. Salvadó


You can just do

var transactionDates = from t in Transactions 
                       select t.FinishTimeStamp;

var dates = new { 
                   FromDate = transactionDates.Min(), 
                   ToDate = transactionDates.Max() 
                };
like image 40
womp Avatar answered Sep 22 '22 08:09

womp