So I've seen a few posts describing this, but can't quite figure it out for my case. I used to have a SQL query that used the PIVOT command to order my table, I am trying to move this logic into our app via LINQ. The table is stored in a DataTable and looks like this.
ObjectName | ColumnName | Property | Value
----------------------------------------------
foo | bar | a | w
foo | bar | b | x
foo | bar | c | y
foo | bar | d | z
foo | test | a | i
foo | test | b | j
foo | test | c | k
foo | test | d | l
I want to morph it into a DataTable that looks like this.
ObjectName | ColumnName | a | b | c | d
---------------------------------------------------
foo | bar | w | x | y | z
foo | test | i | j | k | l
So I tried something like this...
var query = dt.AsEnumerable()
.GroupBy(row => row.Field<string>("ColumnName"))
.Select(g => new {
ColumnName = g.Key,
a = g.Where(row => row.Field<string>("Property") == "a").Select(c => c.Field<string>("Value")),
b = g.Where(row => row.Field<string>("Property") == "b").Select(c => c.Field<string>("Value")),
c = g.Where(row => row.Field<string>("Property") == "c").Select(c => c.Field<string>("Value")),
d = g.Where(row => row.Field<string>("Property") == "d").Select(c => c.Field<string>("Value"))
});
Which doesn't include ObjectName (for some reason was giving me a compile error to add it?). Looking at the debugger ColumnName is showing up right, but the rest is mostly gibberish. Sorry my LINQ skills are pretty sub-par, I'm trying to learn, but get confused easily.
I'm guessing my datatype isn't coming out correctly to be able to use that extension method, but I'm in a bit over my head. Any suggestions?
Edit still getting some errors, I am fighting with this line
DataTable newDT = query.CopyToDataTable();
but I get the error message
The type 'AnonymousType#1' cannot be used as type parameter 'T' in the generic type or method 'System.Data.DataTableExtensions.CopyToDataTable (System.Collections.Generic.IEnumerable)'. There is no implicit reference conversion from 'AnonymousType#1' to 'System.Data.DataRow'.
Try this:
Here is the code that I'm using to copy to the datattable, since you didn't state what you were using: