我正在学习C#中的LINQ。我有以下JSON数据:
std::string
我想通过对产品进行分组来执行LINQ 然后通过降序排序,最后选择前三名。
我该怎么做?在结果中,我必须显示产品及其数量如下:
[
{
"product": [
"a", "b", "c"
]
},
{
"product": [
"a","b"
]
},
{
"product": [
"b","c"
]
},
{
"product": [
"b", "c"
]
},
{
"product": [
"a","b"
]
},
{
"product": [
"b", "c"
]
},
{
"product": [
"a"
]
},
]
我目前的代码是:
"b","c" 3
"a","b" 2
"a","b","c" 1
但我得到全部1作为计数。你能帮忙纠正一下结果吗?谢谢。
答案 0 :(得分:0)
您正尝试按序列分组,但没有自定义比较器。那不行 要获得所需的输出,请尝试执行以下操作:
public class SequenceComparer : IEqualityComparer<string[]>
{
public bool Equals(string[] x, string[] y)
{
if (ReferenceEquals(x, y))
return true;
if (x == null || y == null)
return false;
return x.SequenceEqual(y);
}
public int GetHashCode(string[] obj)
{
return obj.Aggregate(42, (c, n) => c ^ n.GetHashCode());
}
}
var json = "[\r\n {\r\n \"product\": [\r\n \"a\", \"b\", \"c\"\r\n ]\r\n },\r\n {\r\n \"product\": [\r\n \"a\",\"b\"\r\n ]\r\n },\r\n {\r\n \"product\": [\r\n \"b\",\"c\"\r\n ]\r\n },\r\n {\r\n \"product\": [\r\n \"b\", \"c\"\r\n ]\r\n },\r\n {\r\n \"product\": [\r\n \"a\",\"b\"\r\n ]\r\n },\r\n {\r\n \"product\": [\r\n \"b\", \"c\"\r\n ]\r\n },\r\n {\r\n \"product\": [\r\n \"a\"\r\n ]\r\n },\r\n]";
var products = JsonConvert.DeserializeAnonymousType(json,
new[] {new {product = new string[] { }}});
var result = products.GroupBy(p => p.product, new SequenceComparer())
.Select(g => new {g.Key, Count = g.Count()})
.OrderByDescending(x => x.Count)
.Take(3);
现在你可以看到一个结果:
foreach (var row in result)
Console.WriteLine($"{string.Join(",", row.Key)} {row.Count}");
将输出
'b,c' 3
'a,b' 2
'a,b,c' 1
直播demo