使用 LINQ 透视数据
我有一个包含枚举(TypeCode)和用户对象的项目集合,我需要将其展平以显示在网格中。 这很难解释,所以让我举一个简单的例子。
集合具有如下项目:
TypeCode | User
---------------
1 | Don Smith
1 | Mike Jones
1 | James Ray
2 | Tom Rizzo
2 | Alex Homes
3 | Andy Bates
我需要输出为:
1 | 2 | 3
Don Smith | Tom Rizzo | Andy Bates
Mike Jones | Alex Homes |
James Ray | |
我尝试使用 foreach 执行此操作,但我不能这样做,因为我会将新项目插入到 foreach 中的集合中,从而导致错误。
这可以在 Linq 中以更简洁的方式完成吗?
I have a collection of items that contain an Enum (TypeCode) and a User object, and I need to flatten it out to show in a grid. It's hard to explain, so let me show a quick example.
Collection has items like so:
TypeCode | User
---------------
1 | Don Smith
1 | Mike Jones
1 | James Ray
2 | Tom Rizzo
2 | Alex Homes
3 | Andy Bates
I need the output to be:
1 | 2 | 3
Don Smith | Tom Rizzo | Andy Bates
Mike Jones | Alex Homes |
James Ray | |
I've tried doing this using foreach, but I can't do it that way because I'd be inserting new items to the collection in the foreach, causing an error.
Can this be done in Linq in a cleaner fashion?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我并不是说这是一种伟大的转型方式 - 但它是一个转型......
I'm not saying it is a great way to pivot - but it is a pivot...
马克的答案给出了稀疏矩阵,不能直接输入网格。
我尝试从 Vasu 提供的 链接 扩展代码,如下所示:
* 可以不过,不要谈论任何有关性能的事情。
Marc's answer gives sparse matrix that can't be pumped into Grid directly.
I tried to expand the code from the link provided by Vasu as below:
* can't say anything about the performance though.
我想这与马克的答案类似,但我会发布它,因为我花了一些时间来研究它。 结果由
" | "
分隔,如您的示例所示。 在使用 group by 时,它还使用从 LINQ 查询返回的IGrouping
类型,而不是构造新的匿名类型。 这是经过测试的工作代码。我还使用以下输入对其进行了测试:
产生了以下结果,表明第一列不需要包含最长的列表。 如果需要,您可以使用
OrderBy
获取按 TypeCode 排序的列。I guess this is similar to Marc's answer, but I'll post it since I spent some time working on it. The results are separated by
" | "
as in your example. It also uses theIGrouping<int, string>
type returned from the LINQ query when using a group by instead of constructing a new anonymous type. This is tested, working code.I also tested it with this input:
Which produced the following results showing that the first column doesn't need to contain the longest list. You could use
OrderBy
to get the columns ordered by TypeCode if needed.您可以使用 Linq 的 .ToLookup 以您要查找的方式进行分组。
然后就是将其转化为消费者可以理解的形式的问题。 例如:
将其放入 IEnumerable<> 中 方法,它(可能)会返回 User 集合(列)的集合(行),其中 null 被放入没有数据的列中。
You can use Linq's .ToLookup to group in the manner you are looking for.
Then it's a matter of putting it into a form that your consumer can make sense of. For instance:
Put that in an IEnumerable<> method and it will (probably) return a collection (rows) of collections (column) of User where a null is put in a column that has no data.
@Sanjaya.Tio 我对你的答案很感兴趣,并创建了这个适应,最大限度地减少了 keySelector 的执行。 (未经测试)
@Sanjaya.Tio I was intrigued by your answer and created this adaptation which minimizes keySelector execution. (untested)