C# Generic List<T> 更新项

标签 c# generic-list

我正在使用 List<T>我需要更新列表中的对象属性。

最有效/更快的方法是什么?我知道扫描 List<T> 的索引随着此列表的增长和 List<T> 会变慢不是最有效的更新集合。

那可悲,最好是:

  • 删除匹配对象然后添加一个新对象?
  • 扫描列表索引直到找到匹配的对象,然后更新对象的属性?
  • 如果我有一个集合,让我们使用 IEnumerable,我想将该 IEnumerable 更新到列表中,最好的方法是什么。

stub 代码示例:

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

public class ProductRepository
{
    List<Product> product = Product.GetProduct();
    public void UpdateProducts(IEnumerable<Product> updatedProduct)
    {
    }
    public void UpdateProduct(Product updatedProduct)
    {
    }
}

最佳答案

如果您想要快速查找,您可以考虑使用字典而不是列表。在您的情况下,它将是产品 ID(我假设它是唯一的)。 Dictionary MSDN

例如:

public class ProductRepository
    {
        Dictionary<int, Product> products = Product.GetProduct();
        public void UpdateProducts(IEnumerable<Product> updatedProducts)
        {
            foreach(var productToUpdate in updatedProducts)
            {
                UpdateProduct(productToUpdate);
            }

            ///update code here...
        }
        public void UpdateProduct(Product productToUpdate)
        {
            // get the product with ID 1234 
            if(products.ContainsKey(productToUpdate.ProductId))
            {
                var product = products[productToUpdate.ProductId];
                ///update code here...
                product.ProductName = productToUpdate.ProductName;
            }
            else
            {
                //add code or throw exception if you want here.
                products.Add(productToUpdate.ProductId, productToUpdate);
            }
        }
    }

关于C# Generic List<T> 更新项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53170854/

相关文章:

c# - 必须使用Control.Invoke与在单独线程上创建的控件进行交互

c# - Azure 搜索,精确短语匹配

c# - LINQ join Entities from HashSet's, Join vs Dictionary vs HashSet性能

C# List<T>.BinarySearch 在找不到值时返回值

c# - 如何使用 LINQ 从通用列表中获取下一个合适的值?

c# - 我们可以使用通用列表而不是对象数组 C#

C# system.management 未加载

c# - 引用多个 API 扩展时,无法在 "Release"中构建 W10 UWP 应用

C# 更新组合框绑定(bind)到通用列表

c# - 如何从非常大的列表中按索引有效地删除元素?