转换字典,清单的IEnumerable [英] Convert dictionary with List to IEnumerable
问题描述
我有一本字典:
Dictionary<String, List<Foo>> test = new Dictionary<String, List<Foo>>();
然后我填充这个字典因此为什么我需要的列表,以便我可以调用Add()方法。我的问题是,函数需要返回:
I then populate this dictionary hence why I need the list so I can call Add(). My problem is the function needs to return:
Dictionary<String, IEnumerable<Foo>>
有没有简单的方法来做到这一点没有做明显的,通过我原来词典循环和做?手动
Is there any easy way to do this without doing the obvious and looping through my original dictionary and doing it manually?
推荐答案
这是更有效和更容易使用列表<富>
添加的东西,但它添加到词典<弦乐,IEnumerable的<富>>
。这是没有问题的,因为列表<富>
工具的IEnumerable<富方式>
,它甚至没有必要投
It's more efficient and easier to use the List<Foo>
to add things but add it to a Dictionary<String, IEnumerable<Foo>>
. That's no problem since List<Foo>
implements IEnumerable<Foo>
, it's not even necessary to cast.
因此,像这样的(伪代码):
So something like this(pseudo code):
var test = new Dictionary<String, IEnumerable<Foo>>();
foreach(var x in something)
{
var list = new List<Foo>();
foreach(var y in x.SomeCollection)
list.Add(y.SomeProperty);
test.Add(x.KeyProperty, list); // works since List<T> is also an IEnumerable<T>
}
这篇关于转换字典,清单的IEnumerable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!