【问题标题】:How to return "Grouped by" aggregated result?如何返回“分组依据”聚合结果?
【发布时间】:2014-02-03 06:13:12
【问题描述】:

我试图了解如何在 web.api 界面中按结果返回组,就像这样......

[ActionName("Archive")]
public HttpResponseMessage GetArchiveImport() {
    try {
        var result = _service.QueryFor(x => x.ActionType == ActionType.Import)
            .GroupBy(x => x.InsertDate,
                (key, group) => new {
                    Date = key,
                    Entries = group.ToList()
                }).ToList();

        return Request.CreateResponse(HttpStatusCode.OK, result);
    }
    catch (Exception e) {
        _logger.Error("Failed to retrive import file", e);
    }
    return Request.CreateResponse(HttpStatusCode.InternalServerError);
}

QueryFor 返回 => IEnumerable<History>

我没有得到任何结果,谁能解释一下原因?

【问题讨论】:

  • 您是否尝试调试过您的代码?
  • 您是否缺少选择关键字?
  • 检查过没有按部分分组的结果吗?
  • 我在测试中有 390k 结果集。一切正常
  • 你有什么看法?如果您确定您的测试集完美运行,那么您是如何测试没有得到任何结果的?请记住 groupby 语法不返回 IEnumerable

标签: c# linq asp.net-mvc-4 asp.net-web-api


【解决方案1】:

为什么不简化为这个

var result = _service.QueryFor(x => x.ActionType == ActionType.Import)
            .GroupBy(x => x.InsertDate);

并使用调试器检查结果。如果你没有得到任何数据,那么就是你的 QueryFor 没有返回任何数据。

你的问题真的是这样吗Is there a way to force ASP.NET Web API to return plain text?

您的结果中有数据,但没有按预期将它们通过网络传输?

如果我应该是一个普通的 Web API 方法,你的方法签名应该是这样的

public IEnumerable<IGrouping<DateTime, History>> GetArchiveImport()

好的 - 越来越近了 :) Web API 不知道 IGrouping - 我想你可以通过某种方式注册它。

快速解决方法是创建您自己的 Grouping 类,例如

public class HistoryGroup
{
   public DateTime InsertDate { get; set; }
   public IEnumerable<History> History { get; set; }
}

然后将您的组更改为

var result = _service.QueryFor(x => x.ActionType == ActionType.Import)
            .GroupBy(x => x.InsertDate,
                (key, group) => new HistoryGroup() {
                    InsertDate = key,
                    History = group
                })

并返回result.ToList()

你的函数的返回值是IEnumerable&lt;HistoryGroup&gt;

【讨论】:

  • 请评论一下为什么这被否决了,我没有得到 (key, group) => new { Date = key, Entries = group.ToList() }
  • 我想返回我所展示的确切结果,而不是其他签名和相同的确切分组数据。
  • 好的 - 然后你必须将它序列化为 xml/json/whatever-you-like 你自己。使用上面的签名,您只需 return result.ToList()
  • 这里 stackoverflow.com/a/8508212/2294065 你可以找到更多关于 IGrouping 问题的信息
猜你喜欢
  • 2020-01-17
  • 1970-01-01
  • 2018-08-22
  • 2021-12-06
  • 1970-01-01
  • 1970-01-01
  • 2021-03-30
  • 2020-09-05
  • 2021-09-20
相关资源
最近更新 更多