2013-08-03 59 views
3

我有一个数据表,看起来LIK以下拆分一个数据表分成多个数据表基于列名

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>是contins列名的动态数量,例如,如果名单上列表包含一列:

Supplier 

我想制作一个List<DataTable>或从该表中的数据集和独立表基础上,在清单中列名所以在这种情况下,我由Supplier列只独立的结果会是3个数据表看起来像下面

----------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字符串和SELECT DISTINCT和嵌套循环,但它看起来复杂,我不知道是否有才达到更有效的方式这

回答

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); 
}