LINQ 从 IGrouping 转换为 Lookup
我有两个 ILookup 类型的变量。我想使用 Union 或 Concat 组合它们的值并将结果分配给相同类型的第三个变量。 Union 和 Concat 都返回 IGrouping。将 IGrouping 转换为 ILookup 一定非常简单,但我就是做不到! :-( IGrouping 仅公开键,因此我正在努力处理查找的第二个参数......任何帮助将非常非常感谢。
I have two variables of type ILookup. I wanted to use Union or Concat to combine their values and assign the result to a third variable of the same type. Both Union and Concat return IGrouping. It must be dead simple to convert IGrouping to the ILookup but I just can't do it!!! :-( IGrouping exposes just the Key so I am struggling with the second parameter of the Lookup.... Any help will be much, much appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为您需要首先展平序列,以使用
ToLookup
:它使用
SelectMany
的形式,它需要两个委托:一个用于转换原始序列中的项目到一个集合,另一个获取原始集合中的项目(即组)和返回集合中的项目(即与该组的键匹配的项目)以获取结果项目。这是将分组扁平化为带有键的项目序列的最简单方法(我认为!)。以上未经测试,因此可能完全错误。它的效率也相对较低……遗憾的是没有办法直接构建
Lookup
的实例。当然,您可以自己实现ILookup
。I think you'll need to flatten the sequences first, to use
ToLookup
:That uses the form of
SelectMany
which takes two delegates: one to convert an item in the original sequence to a collection, and another to take an item in the original collection (i.e. the group) and an item in the returned collection (i.e. the items matching that group's key) to get to the result item. This is the simplest way (I think!) of flattening a grouping into a sequence of items with their keys.The above isn't tested, so could be completely wrong. It's also relatively inefficient... it's a shame that there's no way of building an instance of
Lookup
directly. You could implementILookup
yourself, of course.