【问题标题】:Which datastructure better now?现在哪种数据结构更好?
【发布时间】:2012-02-16 02:30:13
【问题描述】:

我以前有这样的数据库

ItemName  Price

针对商品名称,我在哈希表中找到了价格。我的一些代码是这样的

Hashtable pricesTilesBox = new Hashtable();
string  itemNameData=myReader["ItemName"].ToString().Trim();
int price=Convert.ToInt32(myReader["Price"]);
pricesTilesBox.Add(itemNameData,price);
foreach (string key in pricesTilesBox.Keys) 
{
 Console.WriteLine(key + '=' + pricesTilesBox[key]);
}

但是现在我已经改变了数据库表

ItemName  PriceLight PriceDark

那么现在可以使用哪种数据结构,我可以得到PriceLight PriceDarkitemName。因为现在有两个价格。这种情况下也可以使用hashtable吗?

【问题讨论】:

标签: c#


【解决方案1】:

你为什么不创建一个类Price

public class Price
{
 public decimal PriceLight { get; set; }
 public decimal PriceDark  { get; set; }
}

然后使用Dictionary<string,Price>

【讨论】:

    【解决方案2】:

    如果您仍然希望能够使用哈希表行为来轻松根据其名称查找条目:

    public class Entry {
      public string ItemName { get; set; }
      public int PriceLight { get; set; }
      public int PriceDark { get; set; }
    }
    
    Dictionary<string, Entry> pricesTilesBox = new Dictionary<string, Entry>();
    
    string  itemNameData=myReader["ItemName"].ToString().Trim();
    int light=Convert.ToInt32(myReader["PriceLight"]);
    int dark=Convert.ToInt32(myReader["PriceDark"]);
    pricesTilesBox.Add(itemNameData,new Entry { ItemName = itemNameData, PriceLight = light, PriceDark = dark });
    foreach (string key in pricesTilesBox.Keys) 
    {
     Console.WriteLine(key + '=' + pricesTilesBox[key]);
    }
    

    【讨论】:

      【解决方案3】:

      使用List&lt;TileBox&gt; 怎么样?

      public class TileBox
      {
       public string Name {get; set;}
       public decimal PriceLight {get; set;}
       public decimal PriceDark {get; set;}
      }
      
      List<TileBox> tileBoxes = new List<TileBox>();
      
      //loop here to add TileBoxes to the List
      {
       TileBox tileBox = new TileBox();
       tileBox.Name = myReader["ItemName"].ToString().Trim();
       tileBox.PriceLight = Convert.ToDecimal(myReader["PriceLight"]);
       tileBox.PriceDark = Convert.ToDecimal(myReader["PriceDark"]);
       tileBoxes.Add(tileBox);
      }
      

      这种方式也支持以后添加字段到TileBox。您只需要更改类 TileBox 以保存新字段,并可能通过读取器循环将该字段读入类,其余代码可以保持不变。

      【讨论】:

        【解决方案4】:

        你可以简单地创建一个class 来保存两个项目

        MyClass
        {
            PriceLight;
            PriceDark;
        }
        

        使用相同的Hashtable,但不要插入Price,而是将MyClassobject 插入ItemName

        【讨论】:

          【解决方案5】:

          如果您的属性将来可能再次更改,您可以考虑使用 Tuple 类

          http://msdn.microsoft.com/en-us/library/system.tuple.aspx

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2021-03-30
            • 1970-01-01
            • 1970-01-01
            • 2013-06-15
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2014-12-26
            相关资源
            最近更新 更多