0

I need to iterate over a list and count all the elements with the same id given this model:

public class Product
    {
        public int ProductId { get; set; }
        public string ProductName { get; set; }
    }

I want to check for all the repeated elements in the list and store the count in a variable:

List<Product> productList = new()
            {
                new Product { ProductName = "item1", ProductId = 1},
                new Product { ProductName = "item2", ProductId = 1},
                new Product { ProductName = "item3", ProductId = 2},
                new Product { ProductName = "item4", ProductId = 2},
                new Product { ProductName = "item5", ProductId = 3},
                new Product { ProductName = "item6", ProductId = 1}
            };

Given the example above, the result should look like this:

int someProduct1 = 3;
int someProduct2 = 2;
int someProduct3 = 1;

How can I achieve something like that?

Jaracara11
  • 17
  • 3
  • Answer is [here](https://www.techiedelight.com/find-duplicates-in-list-csharp/). It was the first match in a Google search for "Find duplicates in a list c#" – Robert Harvey Sep 19 '21 at 14:24

1 Answers1

0

try this

    var query = productList
       .GroupBy(c => c.ProductId)
       .Select(o => new 
       {
           ProductId = o.Key,
           Count = o.Count()
       });

or just repeatings

var query = productList
       .GroupBy(c => c.ProductId)
       .Select(o => new 
       {
           ProductId = o.Key,
           Count = o.Count()
       })
       .OrderByDescending (o => o.Count )
       .Where(p => p.Count>1);

output

productId Count
    1      3
    2      2
Serge
  • 40,935
  • 4
  • 18
  • 45