简体   繁体   English

如何在 Linq 中使用不同的计数?

[英]How can i use distinct with count in Linq?

在此处输入图像描述

The extention method below does not have Distinct and Count下面的扩展方法没有DistinctCount

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM