Home > Backend Development > C++ > How Can LINQ Efficiently Pivot Data from a Wide to a Tall Format for Grid Display?

How Can LINQ Efficiently Pivot Data from a Wide to a Tall Format for Grid Display?

Susan Sarandon
Release: 2025-01-05 16:14:41
Original
375 people have browsed it

How Can LINQ Efficiently Pivot Data from a Wide to a Tall Format for Grid Display?

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:

  1. Group and Select: Group the data by the Enum value and select the user names for each group.
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()
           };
Copy after login
  1. Determine Row Count: Calculate the maximum number of rows based on the length of each group's Bars array.
int rows = grps.Max(grp => grp.Bars.Length);
Copy after login
  1. Output Column Headers: Print the Enum values as column headers.
foreach (var grp in grps) {
    Console.Write(grp.Foo + "\t");
}
Copy after login
  1. Output Data: Iterate through the rows and print the corresponding user names or null for missing values.
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();
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template