【问题标题】:c# How to add data into existing collection itemc#如何将数据添加到现有的集合项中
【发布时间】:2021-04-14 15:53:22
【问题描述】:

我正在尝试将数据添加到现有列表项。目前我有两个不同的收藏。这是我正在使用的以及我正在努力实现的目标的一个子集。

List<Products> products = new List<Products>();
List<Fitment> fitment = new List<Fitment>();


  class Fitment
{

    public string Sku { get; set; }
    public string Model { get; set;  }
    public string Years { get; set; }
  
}

class Products
{

    public string Sku { get; set; }
    public string Price { get; set;  }
    public string Vendor { get; set; }
  
}

我需要做的是匹配配件列表中的 SKU,并将其添加到产品列表中具有相同 SKU 的商品中。一个产品可以有多个配件(例如,用于多辆车的汽车座椅)。产品列表有 100k+ 项,而装修列表有 400k+ 项,所以我正在寻找最快的方法来做到这一点。我尝试了几种处理时间非常长的方法。最快的方法是什么?

【问题讨论】:

  • I have tried several methods that time extremely long to process. 请给我们看其中两个。另外,“极长”是多长时间?
  • 对此的标准解决方案是由 SKU(或有序列表中的 BinarySearch)键入的 Dictionary(或 ConcurrentDictionary)。
  • 不应该Products 拥有一个包含Fitment 集合的属性吗?另外,这些数据是从哪里来的?在创建这些对象期间而不是之后进行聚合可能更有意义
  • 您没有指明列表是否已排序。但无论如何,这根本不会“快”,无论如何,除非你改变数据结构。
  • 另外,“极长”有多长?

标签: c# list foreach


【解决方案1】:

我解决了我的问题。我将产品切换到字典并使用它来将配件数据添加到产品数据中

productFitment.ForEach(fitment =>
           {
               if (dicProducts.ContainsKey(fitment.Sku))
                   dicProducts[fitment.Sku].ProductFitment.Add(fitment);
               else
                   Console.WriteLine(fitment.Sku);

           });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-08
    • 2023-04-05
    • 1970-01-01
    • 2016-04-26
    • 1970-01-01
    • 1970-01-01
    • 2019-09-03
    • 1970-01-01
    相关资源
    最近更新 更多