【问题标题】:Formatting LINQ Query Result Set格式化 LINQ 查询结果集
【发布时间】:2012-03-09 16:33:21
【问题描述】:

我正在开发一个 ASP.NET MVC 应用程序。此应用程序通过 JQuery 执行查询。结果集以 JSON 形式从我的 ASP.NET MVC 控制器返回。在我返回序列化结果集之前,我需要将其缩减为仅我需要的属性。为此,我使用了 LINQ 查询。该 LINQ 查询如下所示:

private IEnumerable RefineResults(ResultList<Result> results)
{           
  // results has three properties: Summary, QueryDuration, and List
  var refined = results.Select(x => new
  {
    x.ID, x.FirstName, x.LastName
  });

  return refined;
}

当我执行此方法时,我注意到精炼不包括原始查询中的 Summary 和 Duration 属性。我希望我的结果集的结构如下:

Summary
QueryDuration
Results
 - Result 1
 - Result 2
 - Result 3
 ...

此时,当我执行 RefineResults 时,我得到了我期望的结果列表。但是,我不知道如何将这些条目放在一个名为“结果”的属性中。我也不知道如何添加“Summary”和“QueryDuration”属性。

有人可以指点我正确的方向吗?

谢谢!

【问题讨论】:

    标签: c# linq


    【解决方案1】:
    private object RefineResults(ResultList<Result> results)
    {           
      // results has three properties: Summary, QueryDuration, and List
      var refined = results.Select(x => new
      {
        x.ID, x.FirstName, x.LastName
      });
    
      return new { Results = refined, Summary = results.Summary, QueryDuration = results.QueryDuration };
    }
    

    您可能希望为此函数的返回值创建一个特定的 DTO 类。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-08
      相关资源
      最近更新 更多