gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 15:33:02 24 4
gpt4 key购买 nike

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

以下是我收集的数据

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com