Linq(MIN&& MAX)

时间:2009-07-10 05:32:30

标签: linq

LINQ

中的sql以下是什么
select MIN(finishTimestamp) AS FromDate, MAX(finishTimeStamp) AS ToDate From Transactions

...

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

由于

3 个答案:

答案 0 :(得分:38)

要在Linq to SQL中使用多个聚合,在表上不分组,我发现避免进行多个查询的唯一方法是创建一个“假组< / em>的“:

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

有点hacky,但生成的SQL很干净,通过这样做,你只对数据库进行一次查询。

答案 1 :(得分:18)

你可以做到

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

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

答案 2 :(得分:0)

如果需要,您也可以使用聚合函数(VB中的示例)

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