2012-07-13 147 views
0

我的數據庫表如下所示:算法來填充詞典<字符串,字典<字符串,字符串>>鍵入對象

Room  Item  Description 
------------------------------------ 
Bedroom  Chair  Leather 
Bedroom  Bed   Comfortable 
Office  Desk  Very Small 
Office  Book Shelf Lot of Books 

我要填充這個數據庫表分爲以下字典類型對象

Dictionary<string, Dictionary<string,string> 

我該怎麼做?

我開始編寫代碼如下,但我不能再繼續,因爲我不知道如何正確填充它。

Dictionary<string, Dictionary<string,string>> roomfurnitures= new Dictionary<string,Dictionary<string, string>>(); 

Dictionary<string, string> furniture= new Dictionary<string, string>(); 

      using (SqlDataReader reader = this.m_cmdGetFurnitureByRoom.ExecuteReader()) 
      { 
       while (reader.Read()) 
       { 
        string roomtype = reader.GetString(reader.GetOrdinal("Room")); 

        string item = reader.GetString(reader.GetOrdinal("Item")); 
        string description = reader.GetString(reader.GetOrdinal("Description")); 

        //I do not know how to populate the roomfurnitures dictionary poperly 
       } 
      } 

在roomfurnitures字典填充正確後,我希望它看起來像這樣。請幫忙。

Bedroom  Chair   Leather     
       Bed    Comfortable 
Office   Desk   VerySmall 
       BookShelf  Lot of Books 

回答

2

重要的是要記住的是,你第一次遇到一個新的房間,你需要實例化它的字典。加入這樣的事情在您的評論的位置:

if (!roomfurnitures.ContainsKey(roomtype)) 
    roomfurnitures[roomtype] = new Dictionary<string, string>(); // the first time we've seen this 

// get the dictionary for the specific room 
var room = roomfurnitures[roomtype]; 

// now we can add the furniture to the room 
room[item] = description; 
+0

-1使用Dictionary.ContainsKey +索引器插入。這不好。 – Grozz 2012-07-14 00:11:52

+0

Brett,這正是我正在尋找的。我試過了,它工作。謝謝 !!!! – 2012-07-14 00:20:59

3

你可以使用一個DataTable充滿DataAdapter,然後用Linq-To-DataSetEnumerable.GroupByEnumerable.ToDictionary

var tblRooms = new DataTable(); 
using(var con = new SqlConnection(connectionString)) 
using (var da = new SqlDataAdapter(sql, con)) 
{ 
    da.Fill(tblRooms); 
} 
Dictionary<string, Dictionary<string,string>> roomGroups = tblRooms 
    .AsEnumerable() 
    .GroupBy(r => r.Field<string>("Room")) 
    .ToDictionary(g => g.Key, g => g.ToDictionary(
     r => r.Field<string>("Item"), 
     r => r.Field<string>("Description"))); 
相關問題