如何获得Dictionary< TKey,TValue>的所有值;作为IList< TValue&gt ;? [英] How do I get all the values of a Dictionary<TKey, TValue> as an IList<TValue>?

查看:62
本文介绍了如何获得Dictionary< TKey,TValue>的所有值;作为IList< TValue&gt ;?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下字典:

IDictionary<int, IList<MyClass>> myDictionary 

我想以IList的形式获取字典中的所有值.

and I am wanting to get all the values in the dictionary as an IList....

只需为我如何进入这种情况添加一些背景知识即可....

Just to add a bit of a background as to how I've gotten into this situation....

我有一个方法可以获取MyClass的列表.然后,我有另一种方法将该列表转换为字典,其中键为MyClass的ID.稍后...并且无法访问该原始列表...我需要获取MyClass的原始未分组列表.

I have a method that gets me a list of MyClass. I then have another method that converts that list into a dictionary where they key is the id for MyClass. Later on...and without access to that original list...I'm needing to obtain the original ungrouped list of MyClass.

当我将myDictionary.Values.ToList()传递给采用IList的方法时,出现编译错误,提示它无法从

When I pass myDictionary.Values.ToList() to a method that takes an IList I get a compile error that says that it can't convert from

System.Collections.Generic.List<System.Collections.Generic.IList<MyClass>> 

收件人:

System.Collections.Generic.IList<MyClass>

现在,我可以理解它已经消失了,并将IList的每个组作为列表的单独元素添加到新列表中....但是在这种情况下,它并不是我真正想要的.我只想要整个字典中所有值的列表.

Now, I can understand that its gone and added each of the groups of IList to the new list as separate elements of the list....but in this instance its not really what I'm after. I just want a list of all the values in the entire dictionary.

那又如何在不遍历字典中的每个键值并创建所需列表的情况下得到我想要的东西呢?

How then can I get what I'm after without looping through each of the key values in the dictionary and creating the list I want?

推荐答案

由于要维护字典(或哈希表)的方式,因此您需要执行此操作.在内部,实现包含键,存储桶(用于冲突处理)和值.您也许可以检索内部值列表,但最好使用以下内容:

Because of how a dictionary (or hash table) is maintained this is what you would do. Internally the implementation contains keys, buckets (for collision handling) and values. You might be able to retrieve the internal value list but you're better of with something like this:

IDictionary<int, IList<MyClass>> dict;
var flattenList = dict.SelectMany( x => x.Value );

它应该可以解决问题;)SelectMany使结果平坦化,这意味着每个列表都被连接成一个长序列(即IEnumerable`1).

It should do the trick ;) SelectMany flattens the result which means that every list gets concatenated into one long sequence (IEnumerable`1).

这篇关于如何获得Dictionary&lt; TKey,TValue&gt;的所有值;作为IList&lt; TValue&gt ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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