gpt4 book ai didi

c# - 如何使用 LINQ 进行双重分组

转载 作者:行者123 更新时间:2023-11-30 17:26:23 25 4
gpt4 key购买 nike

在下面的数据中,我想为每个独特的 parent 找到有多少个独特的订单

    [Fact]
public void Test()
{
var data = new Order[]
{
new Order(){ ParentID =1,ParentName ="Parent 1", OrderID = 11 },
new Order(){ ParentID =1,ParentName ="Parent 1", OrderID = 11 },
new Order(){ ParentID =1,ParentName ="Parent 1", OrderID = 11 },

new Order(){ ParentID =1,ParentName ="Parent 1", OrderID = 22 },
new Order(){ ParentID =1,ParentName ="Parent 1", OrderID = 22 },
new Order(){ ParentID =1,ParentName ="Parent 1", OrderID = 22 },

new Order(){ ParentID =2,ParentName ="Parent 2", OrderID = 33 },
new Order(){ ParentID =2,ParentName ="Parent 2", OrderID = 33 },
new Order(){ ParentID =2,ParentName ="Parent 2", OrderID = 33 },

new Order(){ ParentID =2,ParentName ="Parent 2", OrderID = 44 },
new Order(){ ParentID =2,ParentName ="Parent 2", OrderID = 44 },

new Order(){ ParentID =2,ParentName ="Parent 2", OrderID = 55 },
new Order(){ ParentID =2,ParentName ="Parent 2", OrderID = 55 },
};


var queryResult = data
.GroupBy(x => x.OrderID)
.Select(x => new
{
x.First().ParentID,
x.First().ParentName,
})
.ToList();

var result = queryResult.GroupBy(x => new { x.ParentID, x.ParentName })
.Select(x => new Result()
{
ParentID = x.Key.ParentID,
ParentName = x.Key.ParentName,
Count = x.Count()
})
.ToList();

Assert.Equal(2, result.Count);

var firstParent = result.Where(x => x.ParentID == 1).SingleOrDefault();
Assert.Equal(2, firstParent.Count);

var secondParent = result.Where(x => x.ParentID == 2).SingleOrDefault();
Assert.Equal(3, secondParent.Count);

}

上面的代码是有效的。但我想检查是否有更好的方法(优化)来做到这一点。数据可能有1000+条记录

dotnetfiddle demo

最佳答案

i want to find for each unique parent how many unique orders are there

很简单,获取所有订单,按其父级对它们进行分组(无论您如何标识它们),然后计算这些组中的不同订单(那些具有唯一 OrderId 字段的订单)。

var result =
(from o in data
group o.OrderId by new { o.ParentId, o.ParentName } into g
select new Result
{
ParentId = g.Key.ParentId,
ParentName = g.Key.ParentName,
Count = g.Distinct().Count(),
})
.ToList();

关于c# - 如何使用 LINQ 进行双重分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56780315/

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