带有字符串键的字典中的 KeyNotFoundException

KeyNotFoundException at dictionary with string key

我未能使用字符串键获取值

...
Dictionary<string, Data> dateDic = new Dictionary<string, Data>();
...

public void GetDataList(string _code, int _startDate, int _limit, out List<Data> _list)
{
    _list = (from data in dateDic[_code].Values     // <= System.Collections.Generic.KeyNotFoundException!!!
            where data.date >= startDate
            orderby data.date descending
            select data).Take(_limit).ToList<Data>();
}

变量 _code027410

正在观看 window:

stockShcodeDic[_code] System.Collections.Generic.KeyNotFoundException <= Error stockShcodeDic["027410"] {Base.Data} Base.Data <= OK

字典中没有key,可以用Dictionary.TryGetValue

处理
List<Data> listValues; // Assuimging dateDic[_code].Values  is of type List<Data>
listValues = dateDic.TryGetValue(_code, out value);
_list  = listValues .where(x=>x.data.date >= startDate).orderby(data.date descending).Select(x=>x.data).ToList<Data>();;

甚至更简单

public void GetDataList(string _code, int _startDate, int _limit, out List<Data> _list)
{
    if(dateDic.ContainsKey("_code"))
    {
      return;
    }
    _list = (from data in dateDic[_code].Values     // <= System.Collections.Generic.KeyNotFoundException!!!
            where data.date >= startDate
            orderby data.date descending
            select data).Take(_limit).ToList<Data>();
}