0

我想运行并打印一个查询,显示一天中每小时的订单数(24)。

应该看起来像:
小时-1:00,订单数-5
小时-2:00,订单数-45
小时-3:00,订单数-25
小时-4:00,订单数-3
小时- 5:00,订单数量-43
等等……

我尝试:

    public void ShowBestHours()
    {
        using (NorthwindDataContext db = new NorthwindDataContext())
        {
            var query =
                from z in db.Orders
                select new Stime
                {
                    HourTime = db.Orders.GroupBy(x => x.OrderDate.Value.Hour).Count(),

                };
            foreach (var item in query)
            {
                Console.WriteLine("Hour : {0},Order(s) Number : {1}", item.HourTime, item.Count);
            }
        }
    }
    public class Stime
    {
        public int HourTime { get; set; }
        public int Count { get; set; }

    }
4

3 回答 3

2

您需要将查询更改为

var query = 
    from z in db.Orders
    group z by z.OrderDate.Value.Hour into g
    select new Stime{ HourTime = g.Key, Count=g.Count () };

或者

var query = db,Orders.GroupBy (o => o.OrderDate.Value.Hour).Select (
    g => new Stime{ HourTime=g.Key, Count=g.Count () });

在我的 Northwind 副本中,所有 OrderDate 值都只是日期,因此结果只是 HourTime = 0,Count = 830。

我假设您只是在尝试分组。尝试像这样按星期几分组

var query = db.Orders.GroupBy (o => o.OrderDate.Value.DayOfWeek).Select (
    g => new { DayOfWeek=g.Key, Count=g.Count () });

这给出了更有用的结果。

于 2013-02-17T15:57:46.077 回答
1

您没有Stime.Count在查询中进行任何设置,也没有按小时正确分组。当然,我还没有看到您的确切设置,但我认为以下内容应该适合您。

var query =
    from z in db.Orders
    group z by z.OrderDate.Value.Hour into g
    select new Stime() { HourTime = g.Key, Count = g.Count() };

foreach (var item in query)
{
    Console.WriteLine("Hour : {0},Order(s) Number : {1}", item.HourTime, item.Count);
}
于 2013-02-17T15:57:33.250 回答
1

试试这个:

public void ShowBestHours()
{
    using (NorthwindDataContext db = new NorthwindDataContext())
    {
        var query = db.Orders.GroupBy(x =>  x.OrderDate.Value.Hour).OrderByDescending(x => x.Count()).Select(x => new Stime { HourTime = x.Key, Count = x.Count() });   

        foreach (var item in query)
        {
            Console.WriteLine("Hour : {0},Order(s) Number : {1}", item.HourTime, item.Count);
        }
    }
}
于 2013-02-17T15:58:13.920 回答