[英]How can i use distinct with count in Linq?
The extention method below does not have Distinct
and Count
下面的扩展方法没有
Distinct
和Count
public static IEnumerable<Something> ToFilterModel(this IEnumerable<Product> products)
{
var v = products
.SelectMany(x => x.ProductVariants)
.GroupBy(x => x.OptionId)
.Select(x => new
{
Id = x.Key.ToString(),
Items = x.Select(x => new Item { Id = x.ValueId, Text = x.Value.OptionValue })
});
return v;
}
Given the input below it should return 2 Items
rows and not 3, since i am interested for ValueIds
and also Count
by ValueIds
鉴于下面的输入,它应该返回 2 个
Items
行而不是 3 个,因为我对ValueIds
和按ValueIds
Count
感兴趣
how should i modify it?我应该如何修改它?
More spesifically it should return items with rows 1 and 2 and also更特别的是,它应该返回第 1 行和第 2 行的项目,以及
Count equal to 1 for the first row and Count equal to 2 for the second row.第一行的计数等于 1,第二行的计数等于 2。
You could group by ValueId the grouped options, like:您可以按ValueId对分组选项进行分组,例如:
Items = x
.GroupBy(y => y.ValueId)
.Select(z => new Item { Id = z.Key, Text = z.First().Value.OptionValue, Count = z.Count() })
The result will be:结果将是:
{
"Id":1,
"Items":[
{
"Id":1,
"Text":"text1",
"Count":1
},
{
"Id":2,
"Text":"text2",
"Count":2
}
]
}
NOTE: the Text
is the count of grouped value ids.注意:
Text
是分组值 id 的计数。
The whole code:整个代码:
var v = products
.SelectMany(x => x.ProductVariants)
.GroupBy(x => x.OptionId)
.Select(x => new
{
Id = x.Key.ToString(),
Items = x
.GroupBy(y => y.ValueId)
.Select(z => new Item { Id = z.Key, Text = z.First().Value.OptionValue, Count = z.Count() })
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.