0

我的数据库表如下所示:

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

我想将此数据库表填充到以下 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
4

2 回答 2

3

您可以使用 aDataTable填充 a DataAdapter,然后使用Linq-To-DataSet,Enumerable.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")));
于 2012-07-14T00:05:56.550 回答
2

要记住的重要一点是,当你第一次遇到一个新房间时,你需要实例化它的 Dictionary。在您的评论位置添加类似这样的内容:

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;
于 2012-07-13T23:53:21.377 回答