Linq强制转换为Dictionary
本文关键字:Dictionary 转换 Linq | 更新日期: 2023-09-27 18:19:00
我有一本字典
Dictionary<string, List<MyClass>> MyDictionary = new Dictionary<string,List<MyClass>>();
我正在使用Linq通过键
获取列表(从值)List<MyClass> CurrentList = null;
CurrentList = MyDictionary.Where(d => d.Key.Contains(strKey)).Select(x => x.Value).Cast<Dictionary<string, List<MyClass>>>();
我得到的错误是我不能将字典转换为我的列表。
我错过什么了吗?
谢谢。
试试这个:
由于x.Value
是List<MyClass>
,所以需要使用SelectMany
:
List<MyClass> CurrentList = null;
CurrentList = MyDictionary.Where(d => d.Key.Contains(strKey))
.SelectMany(x => x.Value).ToList();
试试
List<MyClass> CurrentList = null;
CurrentList = MyDictionary.Where(d => d.Key.Contains(strKey)).ToList()
.Where(x => x.Value);
问题就在这里:
.Select(x => x.Value)
x。Value的类型为List<MyClass>
,因此不能将其强制转换为字典。因此,要修改代码,只需使用:
CurrentList = MyDictionary.Where(d => d.Key.Contains(strKey)).Select(x => x.Value).FirstOrDefault();