I’m trying to use Linq to pivot a data table. Trawling through the responses here, and a few other sources I think I’ve managed to get most of the way there but I’m having a little trouble completing the query (entirely as a result of my lack of understanding of Linq, however I’m currently on a tight schedule). The data tables are as follows:
SOURCE:
Name |ItemCode|Rank
----------------------------
-1 |blah1 |1
-1 |blah2 |2
-1 |blah3 |3
-1 |blah4 |4
*PLACEHOLDER*|blah2 |7
*PLACEHOLDER*|blah1 |22
DESIRED OUTPUT:
ItemCode |companyWide|myGroup
----------------------------
blah1 |1 |22
blah2 |2 |7
blah3 |3 |
blah4 |4 |
The code I have currently is:
var temp = reportDataTable.AsEnumerable()
.GroupBy(a => a["ItemCode"]).Select(b => new{ItemCode = b.Key,
companyWide = b.Where(a => (string)a["Name"] == "-1").Select(a => a["Rank"]),
myGroup = b.Where(a => (string)a["Name"] == "*PLACEHOLDER*").Select(a => a["Rank"]) }) ;
The grouping by ItemCode works, but I’m guessing my syntax is wrong in filling the other 2 columns. Any help with this would be greatly appreciated.
Added FirstOrDefault() to items: