Create a cross-tab using Linq

I’m trying to pivot data into a cross-tabulation that resembles:

Route 05/22/19 05/23/19 10 1 20 1 1 

My attempt:

// model public class Route { public string Name { get; set; } public string Scheduled { get; set; } public string Employee { get; set; } } // populate List<Route> routes = new List<Route>(); routes.Add( new Route() { Name = "10", Scheduled = "05/22/19", Employee = "A" }); routes.Add( new Route() { Name = "20", Scheduled = "05/23/19", Employee = "A" }); routes.Add( new Route() { Name = "20", Scheduled = "05/22/19", Employee = "B" }); // pivot (the part that isn't working as expected) var results = from r in routes group r.Scheduled by r.Name into g select new { Foo = g.Key, Bar=g.ToList() }; // display foreach(var item in results) { Console.WriteLine(item.Foo); foreach (string b in item.Bar) { Console.WriteLine(b); } } // 10 05/22/19 20 05/23/19 05/22/19 

I’m missing the count of Employee.

Any suggestions on how to get this to work or improve it would be appreciated.

.Net Fiddle

submitted by /u/badg35
[link] [comments]

Leave a Reply