Pivot Data Using LINQ
In data processing, pivoting refers to transforming data from a format with multiple columns and rows to a format with multiple rows and columns. Here's how you can perform data pivoting using LINQ:
Consider a collection of items containing an TypeCode enum and a User object. As described by the inquiry, you want to flatten the collection and present it in a grid-like structure, as shown in the sample data provided:
TypeCode | User |
---|---|
1 | Don Smith |
1 | Mike Jones |
1 | James Ray |
2 | Tom Rizzo |
2 | Alex Homes |
3 | Andy Bates |
The desired output would be:
1 | 2 | 3 |
---|---|---|
Don Smith | Tom Rizzo | Andy Bates |
Mike Jones | Alex Homes | |
James Ray |
LINQ Solution:
LINQ can efficiently handle this type of pivoting operation. Here's a code snippet that demonstrates how:
// Sample data var data = new[] { new { Foo = 1, Bar = "Don Smith"}, new { Foo = 1, Bar = "Mike Jones"}, new { Foo = 1, Bar = "James Ray"}, new { Foo = 2, Bar = "Tom Rizzo"}, new { Foo = 2, Bar = "Alex Homes"}, new { Foo = 3, Bar = "Andy Bates"}, }; // Group into columns and select rows per column 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() }; // Find the total number of (data) rows int rows = grps.Max(grp => grp.Bars.Length); // Output columns foreach (var grp in grps) { Console.Write(grp.Foo + "\t"); } Console.WriteLine(); // Output data 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(); }
Output:
1 2 3
Don Smith Tom Rizzo Andy Bates
Mike Jones Alex Homes
James Ray
This LINQ solution effectively pivots the data into the desired format by grouping items with the same Foo value and then selecting the Bars (user names) per column. It calculates the maximum number of rows based on the entries in each column and generates the output in a well-structured table form.
The above is the detailed content of How Can I Pivot Data Using LINQ?. For more information, please follow other related articles on the PHP Chinese website!