Das*_*ave 11 c# ienumerable dictionary
我有一本字典:
Dictionary<String, List<Foo>> test = new Dictionary<String, List<Foo>>();
Run Code Online (Sandbox Code Playgroud)
然后我填充这个字典,因此我需要列表,所以我可以调用Add().我的问题是函数需要返回:
Dictionary<String, IEnumerable<Foo>>
Run Code Online (Sandbox Code Playgroud)
是否有任何简单的方法可以做到这一点,而不是通过我的原始字典并手动完成显而易见的循环?
return dictionary.ToDictionary(x => x.Key,x => x.Value.AsEnumerable())
Run Code Online (Sandbox Code Playgroud)
使用List<Foo>添加内容会更高效、更容易,但将其添加到Dictionary<String, IEnumerable<Foo>>. 这没问题,因为List<Foo>Implements IEnumerable<Foo>,甚至不需要强制转换。
所以像这样(伪代码):
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>
}
Run Code Online (Sandbox Code Playgroud)