Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 953
alexandrovdi Avatar asked Dec 28 '22 02:12

alexandrovdi


1 Answers

Use GroupBy LINQ method:

ListIdProducts
    .GroupBy(i => i)
    .Select(g => new { Value = g.Key, Count = g.Count() });
like image 104
mellamokb Avatar answered Jan 11 '23 13:01

mellamokb