我对 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);
最佳答案
您需要调用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();
关于c# - 使用 linq 选择字典列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24606886/