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

时间:2012-04-17 14:10:02

标签: c# linq linq-to-sql

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);
 }

结果是: 五 6 7 五 2 5

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

3 个答案:

答案 0 :(得分:5)

使用GroupBy LINQ方法:

ListIdProducts
    .GroupBy(i => i)
    .Select(g => new { Value = g.Key, Count = g.Count() });

答案 1 :(得分:3)

var query1 = from a in ListIdProducts 
                         group a by new { a } into g
                         select new
                         {
                             item = g.Key,
                             itemcount = g.Count()
                         };

答案 2 :(得分:2)

这是一个相当标准的分组问题。

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