c# - check exists before add to list 和 linq 中的 distinct 之间的性能

标签 c# performance linq

在 foreach 循环中,我想将产品添加到列表中,但我希望此列表不包含重复的产品,目前我有两个想法已解决。

1/在循环中,在将Product添加到List之前,我会检查该Product是否已经存在于List中,否则我将其添加到List。

foreach (var product in products)
{
    // code logic
    if(!listProduct.Any(x => x.Id == product.Id))
    {
        listProduct.Add(product);
    }
}

2/。在循环中,即使有重复的产品,我也会将所有产品添加到列表中。然后在循环之外,我将使用 Distinct 删除重复记录。

foreach (var product in products)
{
    // code logic
        listProduct.Add(product);
}
listProduct  = listProduct.Distinct().ToList();

不知这两种方式是最有效的方式。或者有任何其他想法能够将记录添加到列表中以避免重复??

最佳答案

我会选择第三种方法:HashSet。它有一个接受 IEnumerable 的构造函数重载。 .此构造函数删除重复项:

If the input collection contains duplicates, the set will contain one of each unique element. No exception will be thrown.

来源: HashSet<T> Constructor

用法:

List<Product> myProducts = ...;
var setOfProducts = new HashSet<Product>(myProducts);

删除重复项后 setOfProducts[4] 没有正确的含义.

因此 HashSet 不是 IList<Product> ,而是一个 ICollection<Product> ,你可以计数/添加/删除等等,你可以用列表做的一切。你唯一不能做的就是按索引获取

关于c# - check exists before add to list 和 linq 中的 distinct 之间的性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51510820/

相关文章:

c# - 一系列序列的 2 组组合的交集的并集

c# - 根据时间通过 LINQ to Entities (EF) 连接同一个表

ASP.NET Web API - Entity Framework - 500 内部服务器错误。包含(param => param.field)

c# - 根据 C# 中的表单最大化调整面板宽度

c# - 是否可以在 C# 中将接口(interface)叠加在外部类上?

wpf - 连续填充的 ListView 未虚拟化

C# 性能最佳实践 : object creation vs reuse

c# - 当 DataTemplate 具有可见性绑定(bind)时,WPF ListBox 自动宽度更改不正确

c# - facebook c# sdk 入门

c# - 在锯齿状数组上手动索引?