如何从List获取重复次数

本文关键字:获取 int List | 更新日期: 2023-09-27 18:31:28

List<int> ListIdProducts = new List<int>();
var IdProductKey = from a in me.ProductKeywords where a.Keyword == item.Id select a;
 foreach (var item2 in IdProductKey)
 {
   ListIdProducts.Add(item2.Product.Value);
 }

结果是:567525

我需要得到以下 5=3, 6=1, 7=1, 2=1

如何从List<int>获取重复次数

使用 GroupBy LINQ 方法:

ListIdProducts
    .GroupBy(i => i)
    .Select(g => new { Value = g.Key, Count = g.Count() });
var query1 = from a in ListIdProducts 
                         group a by new { a } into g
                         select new
                         {
                             item = g.Key,
                             itemcount = g.Count()
                         };
这是一个

相当标准的分组问题。

//untested
var IdProducts = from a in me.ProductKeywords 
                 where a.Keyword == item.Id 
                 group by a.Product.Value into g
                 select g.Count();