LINQ将字典转换为查找 [英] LINQ Convert Dictionary to Lookup

查看:128
本文介绍了LINQ将字典转换为查找的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类型为的变量字典< MyType,List< MyOtherType>>

我想将其转换为 Lookup< MyType,MyOtehrType>

我想先使用Lambda函数,平铺字典,然后将其转换为Lookup ToLookup()。我被困在字典里。我想到使用SelectMany,但不能让它工作。任何人都有一个想法如何做?

I wanted to use Lambda functions to first, flatten the dictionary and then convert this to Lookup using the ToLookup(). I got stuck with the dictionary. I thought about using SelectMany but can't get it working. Anyone has got an idea how to do it?

推荐答案

如何:

var lookup = dictionary.SelectMany(pair => pair.Value,
                                   (pair, Value) => new { pair.Key, Value })
                       .ToLookup(pair => pair.Key, pair => pair.Value);

当字典已经具有所有信息分组时,确实感觉到有点浪费适当地,但我看不到一个简单的方法。当然,您可以使用字典周围的包装来实现 ILookup< TKey,TValue>

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...

这篇关于LINQ将字典转换为查找的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆