我有一个对象列表(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
我怎么能这样做? 谢谢你的时间
答案 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();
答案 1 :(得分:0)
您可以在Name和Id参数上使用GroupBy
。对不起,先读错了。