I want to modify my table in a Datatable. I know that I have to use linq and group the results.
Before:
ID Name LastName
1 Kiki ha
3 lola mi
2 ka xe
2 Kiki ha
After:
Name LastName 1 3 2
Kiki ha x x
lola mi x
ka xe x
My original code:
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);
I also tried this but it didn’t work:
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();
This should do what you need:
Note that i output the lowercase names because i needed to group by case insensitive.
Edit: Here’s a screenshot of the
DataTablein the debugger window: