C# 压平字符串字典
我有一行代码:C# 压平字符串字典,c#,linq,C#,Linq,我有一行代码: Dictionary<string,string> alreadyThere = GetItFromFooMethod(); List<string> flatList = alreadyThere.Values.SelectMany(a => a).ToList(); Dictionary alreadyThere=GetItFromFooMethod(); List flatList=alreadyThere.Values.SelectMany
Dictionary<string,string> alreadyThere = GetItFromFooMethod();
List<string> flatList = alreadyThere.Values.SelectMany(a => a).ToList();
Dictionary alreadyThere=GetItFromFooMethod();
List flatList=alreadyThere.Values.SelectMany(a=>a.ToList();
但我得到了这个编译错误:
Cannot implicitly convert type 'System.Collections.Generic.List<char>' to 'System.Collections.Generic.List<string>'
无法将类型“System.Collections.Generic.List”隐式转换为“System.Collections.Generic.List”
为什么它认为我需要
char
?我该如何修复它呢?我想您只需要像这样获取值:
List<string> flatList = alreadyThere.Values.ToList();
List flatList=alreadyThere.Values.ToList();
由于string
是一个IEnumerable
,SelectMany
返回IEnumerable
。它认为您正试图将每个字符分别放入一个列表中。但我认为你不想那样
仅当您有一个IEnumerable
时,扁平化才有用。例如,如果您有一个Dictionary
,那么该代码就可以工作。但在您的情况下,值
集合已经是一个IEnumerable
,因此调用ToList
应该足够了…SelectMany扁平化列表。字符串是一个字符数组。所以你得到了列表