1

我想在数据表中修改我的表。我知道我必须使用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();
4

1 回答 1

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调试器窗口中的屏幕截图:

在此处输入图像描述

于 2012-10-11T14:38:12.323 回答