在下面的数据中,我想找到每个唯一父级有多少个唯一订单。
[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多条记录。
Select(xg => xg.First())
来处理第一个queryResult
? - NetMageGroupBy(f).Select(g => g.First())
是实现DistinctBy(f)
的简单方法。 - NetMage