2012-01-22 116 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

謝謝讓我試試看,謝謝。 –

相關問題