【问题标题】:Dynamic linq query with nested groups具有嵌套组的动态 linq 查询
【发布时间】:2015-10-12 09:11:53
【问题描述】:

我正在尝试使用动态查询创建嵌套组。

以下是我收集的数据

var invoices = new List < Purchase > () {
    new Purchase() {
        Id = 1, Customer = "a", Date = DateTime.Parse("1/1/2009")
    }, new Purchase() {
        Id = 2, Customer = "a", Date = DateTime.Parse("1/2/2009")
    }, new Purchase() {
        Id = 3, Customer = "a", Date = DateTime.Parse("1/2/2009")
    }, new Purchase() {
        Id = 4, Customer = "b", Date = DateTime.Parse("1/1/2009")
    }, new Purchase() {
        Id = 5, Customer = "b", Date = DateTime.Parse("1/1/2009")
    }, new Purchase() {
        Id = 6, Customer = "b", Date = DateTime.Parse("1/2/2009")
    }
 };

此 linq 查询正在返回所需的结果。

  var tree = invoices.GroupBy(x => x.Date).Select(x => new
        {
            Key = x.Key,
            Items = x.GroupBy(y => y.Customer).Select(y => new
            {
                Key = y.Key,
                Items = y
            })
        }).ToList();

以下是上述 linq 查询的输出

但我只需要以不同的顺序对不同的列进行分组。

所以我尝试创建动态 linq 查询。但我的代码块结果与我之前的 linq 查询不同。

var groupedInvoiceItems = invoices.AsQueryable().GroupBy("new (Date, Customer)", "it");

【问题讨论】:

  • 你动态查询的结果是什么?
  • 你说的动态查询是什么意思?是不是和System.Linq.Dynamic有关?
  • 我的意思是动态 LINQ 查询。检查以下链接c-sharpcorner.com/UploadFile/deveshomar/…
  • 这与我的链接中的相同。你需要清楚地说明这些事情,因为你可能会看到这些是非官方的来源,所以没有人应该知道你所说的这些术语是什么意思。具体问题呢,我认为他们不支持您的要求,但当然可能是错误的。祝你好运。

标签: c# linq hierarchy linq-group


【解决方案1】:

您可以使用Generics 执行此操作。只需将您的 Lambda 传递给通用方法。

类似:

private IEnumerable<PurchaseGrp> BuildList<TSource>(IQueryable<TSource> allRecords,
            Func<TSource, string> selector)
{
   var result = allRecords.GroupBy(x = > x.selector(x));
   return result;
}

返回类型可以是新的分组类型 PurchaseGrp 或与您的源 (Purchase) 相同。

【讨论】:

  • 如果您只是将其视为IEnumerable,则不应接受IQueryable。这将不允许在数据库中进行操作。
猜你喜欢
  • 2017-04-28
  • 1970-01-01
  • 1970-01-01
  • 2019-08-02
  • 1970-01-01
  • 1970-01-01
  • 2012-02-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多