Linq如何找到最大重复项?

时间:2017-05-02 14:25:32

标签: c# linq

我有一个对象列表(ProductInfo)。 ProductInfo包含id,名称和选项。

想象一下这个样本,我有这个

     ProductInfo Id => 1, Name => XXX, Option = A
     ProductInfo Id => 1, Name => XXX, Option = B
     ProductInfo Id => 2, Name => DEB, Option = A
     ProductInfo Id => 2, Name => DEB, Option = B
     ProductInfo Id => 2, Name => DEB, Option = C
     ProductInfo Id => 3, Name => ZZZ, Option = D
     ....
....

我们看到产品1和2有两次选项A和B. 我的目标是获取列表中每个产品的最大重复项目。

我想得到这样的结果: Id = 1,Name = XXX = A,count = 2 Id = 2,Name = DEB,count = 2

我怎么能这样做? 谢谢你的时间

2 个答案:

答案 0 :(得分:2)

尝试执行此代码:

 var list = new List<ProductInfo> {
                new ProductInfo { Id = 1, Name = "XXX", Option = "A"},
                new ProductInfo { Id = 1, Name = "XXX", Option = "B" },
                new ProductInfo { Id = 2, Name = "DEB", Option = "A" },
                new ProductInfo { Id = 2, Name = "DEB", Option = "B"},
                new ProductInfo { Id = 2, Name = "DEB", Option = "C" },
                new ProductInfo { Id = 3, Name = "ZZZ", Option = "D" }

            };

            var x = from p in list
                    group p by new { p.Id, p.Name, p.Option } into g
                    select new
                    {
                        Id = g.Key.Id,
                        Name = g.Key.Name,
                        Count = list.Count(m => m.Name == g.Key.Name)
                    };
            var t = x.Distinct();

enter image description here

答案 1 :(得分:0)

您可以在Name和Id参数上使用GroupBy。对不起,先读错了。