![](/img/trans.png)
[英]C# How do I replace objects in one collection with Objects from another collection
[英]How do I quickly create a new collection of objects from a collection of larger objects?
我有四個對象集合:
public static ConcurrentBag<string> ProductCodes;
public static ConcurrentDictionary<string, Product> ProductDictionary;
public static ConcurrentBag<IIMIM00> iimiml; // 37782 items
public static ConcurrentBag<IIMAR00> iimarl; // 73516 items
public static ConcurrentBag<PRODUCTINF> additionall; // 6238 items
public static ConcurrentBag<PF_COSSTO> ProductsAndCosts; // 862096 items
因此,首先,我獲得了一個唯一的產品代碼列表,我想從以下代碼創建新的“產品”對象:
Parallel.ForEach(ProductsAndCosts, i => ProductCodes.Add(i.improd));
ProductCodes = new ConcurrentBag<string>(ProductCodes.Distinct().ToList())
產品類別:
public class Product
{
public IIMIM00 iimim { get; set; }
public List<IIMAR00> iimar { get; set; }
public PRODUCTINF productAdditional { get; set; }
}
我的例程使用產品代碼和產品對象對字典進行排序和創建:
Parallel.ForEach(ProductCodes, SortandCreate);
public static void SortandCreate(string productCode)
{
var product = new Product {iimim = iimiml.Single(x => x.IMPROD.Equals(productCode))};
try
{
product.iimar = iimarl.Where(x => x.ARPROD.Equals(productCode)).ToList();
}
catch (Exception)
{
product.iimar = new List<IIMAR00>();
}
try
{
product.productAdditional = additionall.Single(x => x.PRODUCTCOD.Equals(productCode));
}
catch (Exception)
{
product.productAdditional = new PRODUCTINF();
}
ProductDictionary.TryAdd(productCode, product);
}
嘗試捕獲在那里,因為Product對象不會總是具有IIMAR00或PRODUCTINF的實例。
我提出的解決方案非常慢,在i5上占用了2:30。 我不確定是否有更好的方法來解決此問題。
永遠不要對程序流使用try-catch
,因為拋出處理異常會花費很多時間。 實際上,這是秘密的if-else
。 只需添加一個空檢查,您將獲得因異常處理而浪費的時間:
product.iimar = iimarl.Where(x => x.ARPROD != null
&& x.ARPROD.Equals(productCode))
.ToList();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.