tags:

views:

397

answers:

3
+2  Q: 

Linq (MIN && MAX)

Hello All,

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

+5  A: 

You can just do

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

var dates = new { 
                   FromDate = transactionDates.Min(), 
                   ToDate = transactionDates.Max() 
                };
womp
A: 

You can also use the aggregate functions if you want (Example in VB)

 Dim max = Aggregate tMax In Transactions Select tMax Into Max()
jercra
+4  A: 

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.

CMS
+1 interesting!
womp