2013-08-29 28 views
0

所以我必須從將返回所有在我的商店,並與該產品相關的部門ID的產品數據庫中的兩列。創建字典或IEnumerable的對象

我想要做的是使用list/dictionary/ienumerable集創建一些東西,這樣如果我給一個產品id的函數,它會吐出部門id。目前我遇到了一些麻煩,導致申報正確,需要該部門的幫助。

首先我對產品和類別之間的關係的基礎。然後,我想ProductCategoryCollection返回每個產品和類別/部門的所有映射的集合。我陷入了第二部分,並不確定從哪裏去。

helper.GetProductToCategoryMatching()從數據庫返回的行。

public class ProductAndCategoryID 
{ 
    public ProductAndCategoryID(int product, int category) 
    { 
     this.productID = product; 
     this.categoryID = category; 
    } 

    public int productID; 
    public int categoryID; 
} 

public class ProductCategoryCollection : IEnumerable<ProductAndCategoryID> 
{ 
    public ProductCategoryCollection() 
    { 

    } 

    public List<ProductCategoryCollection> populate() 
    { 
     ShippingClassHelper helper = new ShippingClassHelper(); 
     DataSet ds = new DataSet(); 
     List<ProductCategoryCollection> list = new List<ProductCategoryCollection>(); 

     ds = helper.GetProductToCategoryMatching(); 

     foreach (DataRow row in ds.Tables[0].Rows) 
     { 

     } 

     return new List<ProductCategoryCollection>(); 
    } 
} 

回答

0

現在您只需要在循環中創建一個ProductCategoryCollection對象並將其添加到列表中。

public List<ProductAndCategoryID> populate() 
    { 
     ShippingClassHelper helper = new ShippingClassHelper(); 
     DataSet ds = new DataSet(); 
     List<ProductAndCategoryID> list = new List<ProductAndCategoryID>(); 

     ds = helper.GetProductToCategoryMatching(); 

     foreach (DataRow row in ds.Tables[0].Rows) 
     { 
      var pc = new ProductAndCategoryID(); 
      pc.ProductID = row[0]; 
      pc.CategoryID = row[1]; 

      list.Add(pc); 
     } 

     return list; 
    } 
+0

這個我試過前面但我不能設置'ProductAndCategoryID'的值,或者我想如果我只是從數據庫返回兩行,我需要嗎? –

+0

返回的表是什麼樣的? – Jeremy

+0

'ProductID'具有對應關係的'CategoryID'。因此產品#660在類別137中,將返回'660' | '137' –

0

如果我正確理解你的問題,你的要求,你想獲得一個ProductID映射到CategoryID一本字典,這樣查找可對給定ProductIDCategoryID進行。

如果這是你的問題的一個很好的翻譯,這是你可以做什麼:

var productMap = new ShippingClassHelper() 
    .GetProductToCategoryMatching() 
    .Tables[0].Rows 
    .ToDictionary(row => (int)row[0], row => (int)row[1]); 

它作以下假設:

  • 的「產品ID」字段是一個整數,第一場連續。
  • 「CategoryID」字段是一個整數,並且是行中的第二個字段。
  • 您的數據集不包含重複的「ProductID」值。

現在您可以使用本字典來執行查找。如果你想檢查一個給定的產品ID存在,你可以這樣做:

var containsProduct660 = productMap.ContainsKey(660); 

如果你想獲取給定產品ID類別ID,你可以這樣做:

var categoryIdForProduct660 = productMap[660]; 
相關問題