0

私のDBテーブルは次のようになります。

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

このDBテーブルを次のディクショナリタイプのオブジェクトに入力します

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

DataTableaで満たされた aDataAdapterを使用してLinq-To-DataSetから、Enumerable.GroupByおよびを使用できますEnumerable.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

覚えておくべき重要なことは、新しいルームに初めて遭遇したときは、そのディクショナリをインスタンス化する必要があるということです。コメントの場所に次のようなものを追加します。

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 に答える