我的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..!发布于 2012-09-30 02:23:25
如果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-30 00:17:14
因为col1不能确保数据的唯一性,所以在这里Dictionary<string, Dictionary<string, string>>似乎不是很正确,您可以使用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-30 01:31:22
我有两个解决方案,取决于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);https://stackoverflow.com/questions/12654285
复制相似问题