LINQ 将字典转换为查找
我有一个类型为 Dictionary
的变量
我想将其转换为 Lookup
。
我想首先使用 Lambda 函数展平字典,然后使用 ToLookup()
将其转换为 Lookup。我被字典困住了。我想过使用 SelectMany 但无法让它工作。有人知道如何做吗?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
与 Jon 的方法相同,但避免创建匿名类型:
Same as Jon's method, but avoiding the creation of an anonymous type:
怎么样:
当字典已经将所有信息适当分组时,这样做确实感觉有点浪费,但我看不出有什么简单的方法可以解决这个问题。当然,您可以使用字典的包装器自己实现
ILookup
...How about:
It does feel like a little bit of a waste doing this when the dictionary already has all the information grouped appropriately, but I can't see a simple way round that. Of course you could implement
ILookup<TKey, TValue>
yourself with a wrapper around the dictionary...这里已经有一些答案,但将其放在这里供参考。
这会翻转带有值列表的字典,将这些值作为查找列表的键。
带注释的
Already a few answers here, but putting this here for reference.
This flips a dictionary with a list of values, to having those values as the keys of look up list.
Annotated
不是问题的答案,但我认为这是相关信息,应该发布在这里。
您应该考虑一些边缘情况。所有这些都与字典中的项目有关,这些项目有键,但没有值。
这是预期的行为。字典和查找是为不同的目的而设计的。
Not an answer for the question, but I think this is related information and should be posted here.
There is some edge cases you should take into account. All of them about items of dictionary, which have key, but don't have value.
This is expected behavior. Dictionary and Lookup designed for different purposes.
聚会迟到了,但我认为这应该可行,不需要再次枚举所有内容并创建临时元组/匿名类型。
然后你可以做类似的事情:
Late to the party but I think this should work, without needing to enumerate everything again and create temporary tuples/anonymous types.
Then you can do something like: