我正在尝试使用动态查询创建嵌套组。
以下是我收集的数据
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");
最佳答案
你可以用 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/