2

我无法用字符串键获得价值

...
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

在观察窗口:

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

4

1 回答 1

4

字典中不存在密钥,您可以使用 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>();
}
于 2016-02-14T14:16:47.337 回答