2014-10-30 25 views
0

我有對象四個類別:如何從一組較大的對象中快速創建對象的新集合?

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

嘗試捕獲在那裏,因爲產品對象不會總是有IIMAR00或PRODUCTINF的實例。

我提出的解決方案非常緩慢,在一個i5上超過2:30。我不確定是否有更好的方法來解決這個問題。

回答

0

您不應該爲程序流使用try-catch,因爲拋出處理異常需要很長時間。實際上它是一個隱蔽的if-else。只需添加空值支票,您將獲得異常處理所浪費的時間:

product.iimar = iimarl.Where(x => x.ARPROD != null 
           && x.ARPROD.Equals(productCode)) 
         .ToList(); 
相關問題