Home > Backend Development > C++ > How Can LINQ Efficiently Pivot Data from a Collection of Enums and User Objects for Grid Display?

How Can LINQ Efficiently Pivot Data from a Collection of Enums and User Objects for Grid Display?

Susan Sarandon
Release: 2025-01-06 00:32:39
Original
304 people have browsed it

How Can LINQ Efficiently Pivot Data from a Collection of Enums and User Objects for Grid Display?

Pivot Data using LINQ

In your given scenario, you have a collection containing enums (TypeCode) and User objects that you need to flatten for a grid display. To achieve this, you encounter difficulties when attempting a foreach approach. Fortunately, LINQ offers a more elegant solution.

LINQ Pivot Implementation

Using LINQ, you can pivot the data as follows:

// Assuming you have a collection of items
var data = new[]
{
    new { TypeCode = 1, User = "Don Smith" },
    new { TypeCode = 1, User = "Mike Jones" },
    new { TypeCode = 1, User = "James Ray" },
    new { TypeCode = 2, User = "Tom Rizzo" },
    new { TypeCode = 2, User = "Alex Homes" },
    new { TypeCode = 3, User = "Andy Bates" }
};

// Group the data by TypeCode to form columns
var columns = from item in data
             group item by item.TypeCode;

// Get the total number of rows based on the maximum number of items in each column
int rows = columns.Max(c => c.Count());

// Pivot the data into a two-dimensional array for the grid
string[,] grid = new string[rows, columns.Count()];

int rowIndex = 0;
foreach (var column in columns)
{
    foreach (var item in column)
    {
        grid[rowIndex, column.Key - 1] = item.User;
        rowIndex++;
    }
    rowIndex = 0;
}

// Print the pivot table
Console.WriteLine("Pivot Table:");
for (int i = 0; i < rows; i++)
{
    for (int j = 0; j < columns.Count(); j++)
    {
        Console.Write(grid[i, j] + "\t");
    }
    Console.WriteLine();
}
Copy after login

This implementation groups the data by TypeCode to form columns, calculates the total rows based on the maximum number of items in each column, and pivots the data into a two-dimensional array suitable for grid display.

The above is the detailed content of How Can LINQ Efficiently Pivot Data from a Collection of Enums and User Objects 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