1

我的 DataTable 包含 17 列,其中我正在检索 3 列。例如,我们将这 3 列视为 colA、colB、colC。我的要求是,结果的格式应该是

Dictionary<string, Dictionary<string,string>> ( Dictionary<colA,Dictionary<colB,colC>> )

使用 LINQ 会更好......!

Dictionary<string, Dictionary<string, string>> roles = TA_Roles.GetRoleByUsername(Username)
    .Select(col => new { col.RoleID, col.Rolecode, col.Rolename }) 
    //Please continue from here..!
4

3 回答 3

5

如果 colA 是唯一的,这应该有效:

Dictionary<string, Dictionary<string, string>> result = table.AsEnumerable().ToDictionary(row => row["colA"].ToString(),
                                                                                          row => new string[] { "colB", "colC" }.ToDictionary(col => col, col => row[col].ToString()));
于 2012-09-29T18:23:25.177 回答
1

在这里似乎Dictionary<string, Dictionary<string, string>>没有太多纠正,因为col1不能确保数据是唯一的,您可以List<Tuple<string, string, string>>改用

 var result = table.AsEnumerable().Select(row => 
                Tuple.Create<string, string, string>(row.Field<string>("col1"), 
                                                     row.Field<string>("col2"), 
                                                     row.Field<string>("col3")));
于 2012-09-29T16:17:13.960 回答
1

我有两个解决方案,取决于 col2/col3 组合是否唯一

class Role
{
    public string RoleID { get; set; }
    public string Rolecode { get; set; }
    public string Rolename { get; set; }
}

IEnumerable<Role> source = ...;

Dictionary<string, Dictionary<string, List<string>>> result = source
    .GroupBy(r => r.RoleID)
    .ToDictionary(g => g.Key,
         g => g.GroupBy(r2 => r2.Rolecode)
        .ToDictionary(g2 => g2.Key,
            g2 => g2.Select(r3 => r3.Rolename).ToList())
    );

// Rolecode unique
Dictionary<string, Dictionary<string, string>> result2 = source
    .GroupBy(r => r.RoleID)
    .ToDictionary(g => g.Key,
        g => g.ToDictionary(r2 => r2.Rolecode, r2 => r2.Rolename)
    );

但是如果三列的所有组合都是唯一的,那么整个事情就毫无意义了。但是,创建两个字典是有意义的

Dictionary<string, Role> rolesByID = source.ToDictionary(r => r.RoleID);
Dictionary<string, Role> rolesByCode = source.ToDictionary(r => r.Rolecode);
于 2012-09-29T17:31:21.637 回答