在给定的场景中,您有一个包含枚举 (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中文网其他相关文章!