2009-07-10 104 views
13

什麼是LINQ的LINQ(MIN && MAX)

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

等於以下SQL ??

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

感謝

回答

18

你可以做

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

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

您還可以,如果你想(在VB例)

Dim max = Aggregate tMax In Transactions Select tMax Into Max() 
36

要使用多個聚集使用聚合函數Linq to SQL,在表上,沒有分組,唯一的這樣我發現避免做多個查詢,是做一個「假組」:

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) 
     }; 

還挺哈克,但生成的SQL是乾淨的,並通過這樣做,你做只有一個查詢數據庫。

+0

+1有趣! – womp 2009-07-10 05:53:25