简体   繁体   English

LINQ从IGrouping转换为Lookup

[英]LINQ Convert from IGrouping to Lookup

I have two variables of type ILookup. 我有两个类型ILookup的变量。 I wanted to use Union or Concat to combine their values and assign the result to a third variable of the same type. 我想使用Union或Concat组合它们的值并将结果分配给相同类型的第三个变量。 Both Union and Concat return IGrouping. Union和Concat都返回IGrouping。 It must be dead simple to convert IGrouping to the ILookup but I just can't do it!!! 将IGrouping转换为ILookup一定很简单,但我不能这样做! :-( IGrouping exposes just the Key so I am struggling with the second parameter of the Lookup.... Any help will be much, much appreciated. :-( IGrouping暴露了Key,所以我正在努力寻找Lookup的第二个参数....任何帮助都会非常多,非常感谢。

I think you'll need to flatten the sequences first, to use ToLookup : 我认为你需要首先压扁序列,使用ToLookup

var lookup = first.Concat(second)
                  .SelectMany(group => group,
                              (group, item) => new { Key = group.Key, 
                                                     Item = item })
                  .ToLookup(x => x.Key, x => x.Item);

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 (ie the group) and an item in the returned collection (ie the items matching that group's key) to get to the result item. 它使用SelectMany的形式,它采用两个委托:一个用于将原始序列中的项目转换为集合,另一个用于将原始集合中的项目(即组)和返回集合中的项目(即项目)匹配该组的密钥)以获取结果项。 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. 它的效率也相对较低......很遗憾没有办法直接构建Lookup实例。 You could implement ILookup yourself, of course. 当然,你可以自己实现ILookup

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM