1

我希望 Linq 按日期分组但以文本显示

这是我的代码

var groups = _uow.Orders.GetAll()
            .Where(x => x.Created > baselineDate)
            .GroupBy(x => x.Created.ToString("yyyy-MM-dd"));

var orders = new
        {
            Day = groups.Select(g => g.Key).ToArray(),
            Total = groups.Select(g => g.Sum(t => t.Total)).ToArray(),
        };

结果是(不适合放入图形标签)

 {"Day": [2, 3, 4, 5], "Total": [9999.00, 9999.00, 9999.00, 9999.00] }

但我想要这个(每月)

"Day": ['Jan', Feb', 'Mar', 'Apr'], "Total": [9999.00, 9999.00, 9999.00, 9999.00] }

或每日

"Day": ['Jan 1', 'Jan 2', 'Jan 3', 'Jan 4'], "Total": [9999.00, 9999.00, 9999.00, 9999.00] }

请为我可以玩的 DateTime.ToString() 提供建议。

谢谢你们。

4

3 回答 3

4

谢谢大家的帮助。我找到了答案。

添加

.AsEnumerable()

 .GroupBy(x => x.Created.ToString("MMM d"));

这是完整的代码

var groups = _uow.Orders.GetAll()
            .Where(x => x.Created > baselineDate)
            .AsEnumerable()
            .GroupBy(x => x.Created.ToString("MMM d"));

        var orders = new
        {
            Day = groups.Select(g => g.Key).ToArray(),
            Total = groups.Select(g => g.Sum(t => t.Total)).ToArray(),
        };
于 2013-07-05T15:51:24.777 回答
2

这个问题描述了如何将日期时间转换为月份的字符串名称。

编辑:对于 EF,我们必须在执行任何字符串逻辑之前将所有内容都拉入内存:

var orders = _uow.Orders.GetAll()
    .Where(x => x.Created > baselineDate)
    // pull into memory here, since we won't be making the result set any smaller and
    // we want to use DateTime.ToString(), which EF won't compile to SQL
    .AsEnumerable()
    // this will group by the whole date. If you only want to group by part of the date,
    // (e. g. day or day, month), you could group by x => x.Date.Month or the like
    .GroupBy(x => x.Date)
    .Select(g => new {
        // or use just "MMM" for just the month
        Dates = g.Select(g => g.Key.ToString("MMM d")).ToArray(),
        Total = ...
    });
于 2013-07-04T18:46:51.987 回答
0

您需要使用 EF 可以理解并转换为 SQL 的函数,例如EntityFunctions.TruncateTime. 这是您更新的代码:

var groups = _uow.Orders.GetAll()
            .Where(x => x.Created > baselineDate)
            .GroupBy(x => EntityFunctions.TruncateTime(x.Created));

然后在输出中使用字符串格式,但请确保在将值返回到 .NetAsEnumerable执行此操作,用于切换到 Linq-to-Objects:

var orders = new
        {
            Day = groups.Select(g => g.Key)
                        .AsEnumerable()
                        .Select(x => x.ToString("MMM d"))
                        .ToArray(),
            Total = groups.Select(g => g.Sum(t => t.Total)).ToArray(),
        };
于 2013-07-04T19:42:06.017 回答