tags:

views:

57

answers:

2

I need a C# method that can pivot a DataTable/IDataReader object where the source table contains a composite key.

I wanted to use this: http://weblogs.sqlteam.com/jeffs/articles/5091.aspx however it only works for a single key column.

No SQL, it must be C#.

A: 

You could use LINQ:

myDataTable.AsEnumerable()
    .GroupBy(r => new {col1 = r["col1"], col2 = r["col2"]});

Edit Vertified per comment:

DataTable dataTable = new DataTable();
dataTable.Columns.Add("col1"); 
dataTable.Columns.Add("col2"); 
dataTable.Columns.Add("val");
dataTable.Rows.Add("a", "b", 0);
dataTable.Rows.Add("a", "b", 2);
dataTable.Rows.Add("a", "c", 3);

Console.WriteLine(dataTable.AsEnumerable()
    .GroupBy(r => new { col1 = r["col1"], col2 = r["col2"] }).Count()); //2
Yuriy Faktorovich
I don't understand LINQ very well. When I tried this code I still get back the same number of rows. A pivoted version would denormalize the result set and return a much smaller result set.
subt13
@subt13: I've just tried it and it does return less rows, can you post the code you used?
Yuriy Faktorovich
You're right, I had an extra column in my result set that was causing a problem. However, I need a complete method not only a snippet that will pivot the table. I plan on using the resulting table in data binding situations as well.
subt13
@subt13: You can bind the results of a LINQ expression just like a DataView/DataTable.
Yuriy Faktorovich
A: 

Unfortunately I do not know enough about LINQ to determine if this is a viable solution. I have opted to do my pivot logic at the database level. I'll keep my eyes open.

subt13