【问题标题】:Add values to Hashtable irrespective of index value无论索引值如何,都将值添加到 Hashtable
【发布时间】:2017-03-22 16:23:11
【问题描述】:

我正在从数据库中检索列表中的数据,并希望将其中的两个列存储在哈希表中。但是我只能在索引为 0 的哈希表中插入一行。有没有办法在不考虑索引的情况下插入哈希表?我现在正在使用以下方法。有什么建议吗?

foreach (StoreInfo store_info_id in StoreList)
            {

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

【问题讨论】:

  • 你永远不应该使用HashTable。您应该使用Dictionary
  • @Servy 我不希望此表中的许多条目每次可能都是 3-4,因此我认为 hashtable 将是一个不错的选择。但我愿意接受使用字典执行此操作的建议。
  • 你的 foreach 完全关闭了。迭代器值 store_info_id 从未使用过。
  • @Programmermid 您在集合中拥有的值的数量与我的观点无关。你应该永远使用HashTable。如果您想使用基于哈希的查找,则使用的适当类型是DictionaryHashTable 已过时。
  • 投票关闭,因为错误的非编译伪代码。这里甚至不清楚你想要什么。

标签: c# .net hashtable


【解决方案1】:

三点:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-22
    • 1970-01-01
    • 1970-01-01
    • 2013-07-11
    • 2013-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多