在c#列表中搜索重复元素

  • 本文关键字:元素 搜索 列表 c#
  • 更新时间 :
  • 英文 :


我需要遍历一个列表,并计算给定此模型的所有具有相同id的元素:

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

我想检查列表中所有重复的元素,并将计数存储在一个变量中:

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}
};
在上面的例子中,结果应该是这样的:
int someProduct1 = 3;
int someProduct2 = 2;
int someProduct3 = 1;

我怎样才能做到那样呢?

try this

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

或只是重复

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

输出
productId Count
1      3
2      2

最新更新