我的c#字典有问题。我想检索要使用的列表
ErrDict.Where(x => x.Key == kurumVKN).Select(x => x.Value) as List<ErrorModel>;
但它返回null。我怎样才能获得字典的列表?
Dictionary<string,List<ErrorModel> ErrDict = new Dictionary<string,List<ErrorModel>();
if (ErrDict == null)
{
ErrDict = new Dictionary<string, List<ErrorModel>>();
}
List<ErrorModel> listErrModel = ErrDict.Where(x => x.Key == kurumVKN).Select(x => x.Value) as List<ErrorModel>;
if (listErrModel == null)
{
listErrModel=new List<ErrorModel>();
}
listErrModel.Add(errModel);
ErrDict.Remove(kurumVKN);
ErrDict.Add(kurumVKN, listErrModel);
答案 0 :(得分:2)
您需要在ToList
和Select
之后致电SelectMany
以展开返回List<ErrorModel>
列表的查询。试试这个:
var list = ErrDict.Where(x => x.Key == kurumVKN)
.Select(x => x.Value)
.SelectMany(x => x) // we add this to get only a single List<ErrorModel>
.ToList();
答案 1 :(得分:1)
你可以尝试这个:
var result = ErrDict.Where(x => x.Key == kurumVKN).Select(x => x.Value).ToList();
为了避免Adam在他的评论中正确指出,你必须将上述内容更改为以下内容:
var result = ErrDict.Where(x => x.Key == kurumVKN).SelectMany(x => x.Value).ToList();
答案 2 :(得分:1)
首先,您应该尝试
ErrDict.Where(x => x.Key == kurumVKN).SelectMany(x => x.Value).ToList<ErrorModel>();
答案 3 :(得分:1)
试试这个
List<ErrorModel> listErrModel = ErrDict.Where(x => x.Key == kurumVKN)
.SelectMany(x => x.Value)
.ToList<ErrorModel>();