Pivot Data with LINQ
In data science, pivoting transforms data from a wide format to a tall format or vice versa. Suppose you have a dataset with items containing an Enum and a User object and need to flatten it for a grid display. A straightforward method involves nested foreach loops, but this approach can introduce errors due to changing collection size.
The LINQ Pivot Approach
LINQ provides a cleaner and more efficient way to pivot data:
var grps = from d in data group d by d.Foo into grp select new { Foo = grp.Key, Bars = grp.Select(d2 => d2.Bar).ToArray() };
int rows = grps.Max(grp => grp.Bars.Length);
foreach (var grp in grps) { Console.Write(grp.Foo + "\t"); }
for (int i = 0; i < rows; i++) { foreach (var grp in grps) { Console.Write((i < grp.Bars.Length ? grp.Bars[i] : null) + "\t"); } Console.WriteLine(); }
This code elegantly performs the data pivoting, providing a clean and efficient solution for flattening complex datasets into a grid format.
The above is the detailed content of How Can LINQ Efficiently Pivot Data from a Wide to a Tall Format for Grid Display?. For more information, please follow other related articles on the PHP Chinese website!