我有两个解决方案,取决于 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);