指定されたシナリオでは、グリッド表示用にフラット化する必要がある列挙型 (TypeCode) と User オブジェクトを含むコレクションがあります。これを達成するには、foreach アプローチを試みるときに問題が発生します。幸いなことに、LINQ は、より洗練されたソリューションを提供します。
LINQ を使用すると、次のようにデータをピボットできます。
// 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(); }
この実装では、データがグループ化されます。 TypeCode を使用して列を形成し、各列の項目の最大数に基づいて合計行を計算し、データをグリッド表示に適した 2 次元配列に変換します。
以上がLINQ はグリッド表示のために列挙型とユーザー オブジェクトのコレクションからデータを効率的にピボットするにはどうすればよいですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。