在給定的場景中,您有一個包含枚舉(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形成列,根據每列中的最大項目數計算總行數,並將資料旋轉為適合網格的二維數組顯示。
以上是LINQ 如何有效透視枚舉和使用者物件集合中的資料以進行網格顯示?的詳細內容。更多資訊請關注PHP中文網其他相關文章!