2016-11-08 18 views
-1

我從數據庫中檢索列表中的數據,並希望將其兩個列存儲在散列表中。但是我能夠在索引爲0的散列表中只插入一行。有沒有一種方法可以插入散列表而不考慮索引?我現在正在使用下面的方法。有什麼建議麼?無論索引值如何,都將值添加到散列表中

foreach (StoreInfo store_info_id in StoreList) 
      { 

       Hashtable hashTable = new Hash table(); 
       hashTable.Add(StoreList[0].store_info_id, StoreList[0].RetailControlNumber); 
      } 
+2

你應該永遠不會成爲使用'HashTable'。你應該使用'Dictionary'。 – Servy

+0

@Servy我不希望這個表中的許多條目可能每次都是3-4,所以散列表本來是我認爲的一個好選擇。但我願意使用字典進行此操作。 – Programmermid

+0

你的foreach是完全關閉的。迭代器值store_info_id從不使用。 –

回答

2

三點:

  1. Hashtable只是Dictionary<object, object>,之前有可能有類型參數。所以,今天再也沒有什麼好的理由可以使用Hashtable,除非你是在與Hashtable是唯一的選擇時寫回的遺留代碼接口。

  2. 如果你想要把列到字典中的同一條目,做了正確的方法是創建一個類型來表示在字典中的記載:然後

    public class StoreRecord 
    { 
        public int StoreInfoID; 
        public string Column1; 
        public string Column2; 
    } 
    

    ,使用Dictionary<int, StoreRecord>

    var records = new Dictionary<int, StoreRecord>(); 
    
    foreach (var storeDatabaseRow in storeList) 
    { 
        var record = new StoreRecord(); 
    
        record.StoreInfoID = storeDatabaseRow.store_info_id; 
        record.Column1 = storeDatabaseRow.Column1; 
        record.Column2 = storeDatabaseRow.Column2; 
    
        records[record.StoreInfoID] = record; 
    } 
    
  3. 如果你的數據庫中的記錄是重量輕,斷開,爲什麼不只是指從字典中的整個數據庫記錄?

    var records = new Dictionary<int, StoreInfo>(); 
    
    foreach (var storeDatabaseRow in storeList) 
        records[storeDatabaseRow.store_info_id] = storeDatabaseRow; 
    

    ,或者使用LINQ:

    var records = storeList.ToDictionary(keySelector: row => row.store_info_id);