alexandrovdi
alexandrovdi

Reputation: 301

how to get the number of repetitions from List<int>

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

Result is: 5 6 7 5 2 5

I need to get the following 5=3, 6=1, 7=1, 2=1

Upvotes: 4

Views: 269

Answers (3)

Pravin Pawar
Pravin Pawar

Reputation: 2569

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

Upvotes: 3

Henk Holterman
Henk Holterman

Reputation: 273439

This a fairly standard group-by problem.

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

Upvotes: 2

mellamokb
mellamokb

Reputation: 56779

Use GroupBy LINQ method:

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

Upvotes: 5

Related Questions