【问题标题】:DataTable to Dictionary<string, Dictionary<string,string>>DataTable 到 Dictionary<string, Dictionary<string,string>>
【发布时间】:2012-09-21 04:21:01
【问题描述】:

我的数据表包含 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..!

【问题讨论】:

    标签: c# linq dataset


    【解决方案1】:

    似乎Dictionary&lt;string, Dictionary&lt;string, string&gt;&gt; 在这里没有更正,因为col1 不能确保数据是唯一的,您可以改用List&lt;Tuple&lt;string, string, string&gt;&gt;

     var result = table.AsEnumerable().Select(row => 
                    Tuple.Create<string, string, string>(row.Field<string>("col1"), 
                                                         row.Field<string>("col2"), 
                                                         row.Field<string>("col3")));
    

    【讨论】:

    • 但是 colA 是表中的主键,我会通过 colA 引用 Dictionary
    • @Praveen:一个数据colA只有一个数据在colB,一个数据在colC,不应该是字典
    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      如果 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()));
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-03-01
        • 2018-08-04
        • 1970-01-01
        • 1970-01-01
        • 2014-10-22
        • 1970-01-01
        • 2010-09-24
        • 1970-01-01
        相关资源
        最近更新 更多