Linq查询按日期对项目进行计数和分组

时间:2016-03-18 09:48:52

标签: c# .net linq

我有一组Orders来自EF。每个Order都有一个订单日期:

public class Order {
    public DateTime Date { get; set; }
    public int Id { get; set; }
}

我希望能够运行查询以返回特定日期范围内每天的订单数量。查询方法应如下所示:

public class ICollection<OrderDateSummary> GetOrderTotalsForDateRange(DateTime startDate, DateTime endDate) {

      var orderDateSummary = Set.SelectMany(u => u.Orders) // ..... grouping/totalling here?!

      return orderDateSummary;
}

有关信息,Set实际上是存储库的一部分,它返回用户聚合根,因此Set的类型为DbSet<User>我坚持的位是分组和总计可以从Orders方法查询SelectMany

OrderDateSummary类如下所示:

public OrderDateSummary {
      DateTime Date { get; set; }
      int Total { get; set; }
}

因此,开始日期为01/01/2016和结束日期为03/01/2016的输出看起来像:

Date          Total
===================
01/01/2016       10
02/01/2016        2
03/01/2016        0
04/01/2016       12

4 个答案:

答案 0 :(得分:2)

var startDate = new DateTime (2016, 1, 1);
var endDate = new DateTime (2016, 1, 4);

Set.SelectMany(u => u.Orders).
    Where (order => startDate <= order.Date && order.Date <= endDate) // If filter needed
    GroupBy (order => order.Date, (date, values) =>
        new OrderDateSummary () {
            Date = date,
            Total = values.Count ()
        }).
    OrderBy (summary => summary.Date).
    ToList ();

您应该使用OrderDateSummaryclass标记struct,并将这些属性设为public或添加构造函数。

你有一个预期结果的日期04/01/2016,所以,我想,你的结束时间是第4而不是第3。

答案 1 :(得分:1)

怎么样

List<OrderDateSummary> Result = OrderList       
    .Where(x => x.Date >= startDate && x.Date <= endDate)
    .GroupBy(x => x.Date)
    .Select(z => new OrderDateSummary(){
          Date = z.Key, 
          Total = z.Count()
     }).OrderBy(d=> d.Date).ToList();

答案 2 :(得分:1)

我可以看到您需要生成从startend范围内的所有日期。然后计算每个日期的订单总数。

DateTime start = new DateTime(2016, 1, 1);
DateTime end = new DateTime(2016, 1, 4);
Enumerable
    .Range(0, 1 + (end - start).Days)
    .Select(x => start.AddDays(x))
    .GroupJoin(Set.SelectMany(u => u.Orders),
        dt => dt, o => o.Date.Date,
        (dt, orders) => new OrderDateSummary { Date = dt, Total = orders.Count() })
    .ToList();

查看working example on Ideone

答案 3 :(得分:0)

尝试下面的代码是linq

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace ConsoleApplication82
{
    class Program
    {
        static void Main(string[] args)
        {
            List<OrderDateSummary> orderSummary = null;

            DataTable dt = new DataTable();
            dt.Columns.Add("id", typeof(int));
            dt.Columns.Add("date", typeof(DateTime));
            dt.Columns.Add("amount", typeof(decimal));

            dt.Rows.Add(new object[] { 1, DateTime.Parse("1/1/16"), 1.00 });
            dt.Rows.Add(new object[] { 2, DateTime.Parse("1/1/16"), 2.00 });
            dt.Rows.Add(new object[] { 3, DateTime.Parse("1/2/16"), 3.00 });
            dt.Rows.Add(new object[] { 4, DateTime.Parse("1/2/16"), 4.00 });
            dt.Rows.Add(new object[] { 5, DateTime.Parse("1/2/16"), 5.00 });
            dt.Rows.Add(new object[] { 6, DateTime.Parse("1/3/16"), 6.00 });
            dt.Rows.Add(new object[] { 7, DateTime.Parse("1/3/16"), 7.00 });

            orderSummary = dt.AsEnumerable()
                .GroupBy(x => x.Field<DateTime>("date"))
                .Select(x => new OrderDateSummary() { Date = x.Key, Total = x.Count() })
                .ToList();
        }

    }
    public class OrderDateSummary {
      public DateTime Date { get; set; }
      public int Total { get; set; }
    }
}