2

早上我想知道如何在 LINQ 中执行这一点(MS)SQL ......

 SELECT CONVERT(CHAR(10),orderDate,110)  AS OrderDate, 
 SUM(1) AS TotalOrders 
 FROM Orders
 WHERE OrderDate>getdate()-30
 GROUP BY CONVERT(CHAR(10),orderDate,110)
 ORDER BY OrderDate DESC

提前谢谢了。

更新 我结束了使用和编辑下面提供的解决方案的版本,以为我会分享它......

 using (DataDataContext dc = new DataDataContext())
        {
            var query = from o in dc.Orders
                        where o.orderDate > DateTime.Now.AddDays(-30)
                        let dt = o.orderDate
                        group o by new DateTime(dt.Year, dt.Month, dt.Day) into g
                        select new OrderCounts
                        {
                            OrderDate = String.Format("{0:d}", g.Key.Date),
                            TotalOrders = g.Count()
                        };

            query.GroupBy(o => o.OrderDate);
            query.OrderBy(o => o.OrderDate);

            return query.ToList();
        }
4

2 回答 2

2
var result =(from s in Orders
             where s.OrderDate > DateTime.Now.AddDays(-30)
             group s by new { date = s.OrderDate.ToString() } into g
             // or use ((DateTime)s.OrderDate).ToShortDateString() instead of s.OrderDate.ToString()
             select new
             {
                  OrderDate = g.Key.date,
                  TotalOrders = g.Count()
             }).OrderByDescending(x=>x.OrderDate);;
于 2012-07-27T09:03:00.533 回答
1

查询将是

var query = from o in res
                        where o.OrderDate > DateTime.Now.AddDays(-30)
                        orderby o.OrderDate descending
                        group o by o.OrderDate into g                       
                        select new
                        {
                            OrderDate = g.Key.Date.ToString("MM/dd/yyyy")
                            ,
                            TotalOrders = g.Sum(i=> 1)
                        };

或通过 Lambda 表达式

var query= res
                        .Where(i => i.OrderDate > DateTime.Now.AddDays(-30))
                        .OrderByDescending(o => o.OrderDate)
                        .GroupBy(g => g.OrderDate)
                        .Select(s => new { OrderDate = s.Key.Date.ToString("MM/dd/yyyy"), TotalOrders = s.Sum(i => 1) });
于 2012-07-27T09:45:03.717 回答