首页 文章

根据列名列表将数据表拆分为多个数据表

提问于
浏览
3

我有一个看起来像以下的数据表

ID        Country      Supplier
515       DE           A
515       CH           A
515       FR           A
516       DE           B
516       FR           B
517       DE           C
517       IT           C

我有一个 List<string> ,它包含动态数量的列名,例如,如果列表包含一个列:

Supplier

我想从这个表生成一个 List<DataTable> 或一个DataSet,并根据该列表中的列名分隔表,所以在这种情况下,我只分离 Supplier 列,结果将是3个DataTables,如下所示

----------table 1--------
    515       DE           A
    515       CH           A
    515       FR           A
    ----------table 2--------
    516       DE           B
    516       FR           B
    ----------table 3--------  
    517       DE           C
    517       IT           C

但是如果列名的 List<string> 包含例如以下内容:

Supplier
Country

结果将是7个数据表,每个数据表包含一行

----------table 1--------
    515       DE           A
    ----------table 2--------
    515       CH           A
    ----------table 3--------
    515       FR           A
    ----------table 4--------
    516       DE           B
    ----------table 5--------
    516       FR           B
    ----------table 6--------  
    517       DE           C
    ----------table 7--------
    517       IT           C

另一个例子是,如果 List<string> 列名只包含 Country 列,那么结果将是

----------table 1--------
515       DE           A
516       DE           B
517       DE           C
----------table 2--------
515       CH           A
----------table 3--------
515       FR           A
516       FR           B
----------table 4--------
517       IT           C

我怎样才能使用linq实现这一点,根据列表中包含的列名称查询将是动态的,您能指导我吗?

我已经完成它已经使用DataTable.Select和选择不同和嵌套循环的daynamic字符串,但它看起来很复杂,我想知道是否有更有效的方法来实现这一点

1 回答

  • 1

    你可能想用System.Linq.Dynamic

    var dt = new DataTable();
    var res = new List<DataTable>();
    
    dt.Columns.Add("ID", typeof(int));
    dt.Columns.Add("Country", typeof(string));
    dt.Columns.Add("Supplier", typeof(string));
    dt.Rows.Add(515, "DE", "A");
    dt.Rows.Add(515, "CH", "A");  
    dt.Rows.Add(515, "FR", "A");
    dt.Rows.Add(516, "DE", "B");
    dt.Rows.Add(516, "FR", "B");
    dt.Rows.Add(517, "DE", "C");
    dt.Rows.Add(517, "IT", "C");
    
    var fields = new List<string>() { "Supplier", "Country"};
    var qfields = string.Join(", ", fields.Select(x => "it[\"" + x + "\"] as " + x));
    // qfields = "it[\"Supplier\"] as Supplier, it[\"Country\"] as Country"
    
    var q = dt
        .AsEnumerable()
        .AsQueryable()
        .GroupBy("new(" + qfields + ")", "it")
        .Select("new (it as Data)");
    foreach (dynamic d in q)
    {
        var dtemp = dt.Clone();
    
        foreach (var row in d.Data)
            dtemp.Rows.Add(row.ItemArray);
    
        res.Add(dtemp);
    }
    

相关问题