c# - 具有嵌套组的动态 linq 查询

标签 c# linq hierarchy linq-group

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

以下是我收集的数据

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查询的输出

Output of linq query result

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

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

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

最佳答案

你可以用 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)。

关于c# - 具有嵌套组的动态 linq 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33077309/

相关文章:

tags - 如何对生命、宇宙、万物进行标记和分类?

c# - 不区分大小写的字符串。包含 IEnumerable 和 IQueryable

asp.net-mvc - 如何将两个 LINQ 连接表从 Controller 传递到 View

java - 在类层次结构中设置变量

c# - CLR/C# 中的 “default indexed property” 是什么?

c# - WCF中如何通过LINQ获取Json数据?

javascript - d3树状图使每个矩形大小代表它的值

c# - 两套 Controller

c# - 使用 block 时的编译器错误

c# - 我的 TDD 算法练习