如何使用LINQ进行双重分组

时间:2019-06-26 20:21:07

标签: c# performance linq

在下面的数据中,我想为每个唯一的父级查找有多少个唯一的订单

    [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

1 个答案:

答案 0 :(得分:1)

  

我想为每个唯一的父级查找有多少个唯一的订单

简单,接受所有订单,将其按父级分组(无论您如何识别),然后计算这些组(具有唯一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(); 字段的组)中的不同订单。

CountDownLatch