2012-01-22 118 views
0

我有数据库筛选之前现在哪些数据结构更好?

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。因为有两个现在的价格。哈希表可以用在这种情况下吗?

+0

这个线程可以帮助http://stackoverflow.com/questions/166089/what-is-c-sharp-analog-of-c-stdpair使两个_Price_值中的一对,并添加对到Hashtable –

回答

1

如何使用List<TileBox>

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类来保存新字段,并且可能需要阅读器循环将字段读入类中,而其余代码可以保持不变。

0

那么你可以简单地保持两块项目

MyClass 
{ 
    PriceLight; 
    PriceDark; 
} 

使用,但同样Hashtable而不是插入Price插入MyClassobject针对ItemName创建class

1

你为什么不创建一个类Price为:

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

然后用Dictionary<string,Price>

1

如果您仍然希望能够使用容易查找基于其名的条目哈希表的行为:

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]); 
} 
+0

谢谢让我试试看,谢谢。 –

相关问题