用于填充Dictionary的算法<string,dictionary <string,string>&gt; type object </string,dictionary <string,string>

时间:2012-07-13 23:42:52

标签: c# dictionary

我的数据库表如下所示:

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

我想将此DB表填充到以下Dictionary类型对象

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 个答案:

答案 0 :(得分: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")));

答案 1 :(得分: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;