数据表修改列的行

时间:2012-10-11 14:15:40

标签: c# datatable multiple-columns

我想在Datatable中修改我的表。我知道我必须使用linq并对结果进行分组。 之前:

ID     Name   LastName
1      Kiki    ha 
3      lola    mi 
2      ka      xe 
2      Kiki    ha

后:

Name  LastName   1   3   2
Kiki   ha        x       x
lola   mi            x
ka     xe                x

我的原始代码:

    DataTable table1 = new DataTable("table"); 
    table1.Columns.Add("ID", typeof(String)); 
    table1.Columns.Add("Name", typeof(String)); 
    table1.Columns.Add("Lastname", typeof(String)); 

    object[] a1 = { 1, "Kiki", "ha" }; 
    object[] a2 = { 3, "lola", "mi" }; 
    object[] a4 = { 2, "ka", "xe" }; 
    object[] a5 = { 2, "kiki", "ha" };
    table1.Rows.Add(a1); 
    table1.Rows.Add(a2); 
    table1.Rows.Add(a4);        
    table1.Rows.Add(a5); 

我也尝试了这个,但它不起作用:

    var result = from t1 in table1.AsEnumerable()
                 group t1 by new {ID = t1.Field<String>("ID")} into grp
                  select new
                     {
                         ID = grp.Key.ID,
                         //something must be there
                     };
     DataGridView1.DataSource = result.ToList();

1 个答案:

答案 0 :(得分:2)

这应该做你需要的:

var nameGroups = from row in table1.AsEnumerable()
                 group row by new
                 {
                     Name = row.Field<string>("Name").ToLower(),
                     LastName = row.Field<string>("Lastname").ToLower(),
                 } into NameGroups
                 select NameGroups;

var tblOut = new DataTable();
tblOut.Columns.Add("Name");
tblOut.Columns.Add("LastName");
var distinctIDs = table1.AsEnumerable()
                        .Select(r => r.Field<string>("ID"))
                        .Distinct();

foreach (var id in distinctIDs)
    tblOut.Columns.Add(id);

foreach (var grp in nameGroups)
{
    var row = tblOut.Rows.Add();
    row.SetField<string>("Name", grp.Key.Name);
    row.SetField<string>("LastName", grp.Key.LastName);
    foreach (DataColumn idCol in tblOut.Columns.Cast<DataColumn>().Skip(2))
    {
        bool userHasID = grp.Any(r => r.Field<string>("ID") == idCol.ColumnName);
        row.SetField<string>(idCol, userHasID ? "x" : "");
    }
}

请注意,我输出小写名称,因为我需要按大小写不敏感分组。

修改:以下是调试器窗口中DataTable的屏幕截图:

enter image description here