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?