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 和 Select distinct 和嵌套循环使用了一个动态字符串,但它看起来很复杂,我想知道是否有更有效的方法来实现这一点

4

1 回答 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);
}
于 2013-08-03T11:14:27.493 回答