【问题标题】:KeyNotFoundException at dictionary with string key带有字符串键的字典中的 KeyNotFoundException
【发布时间】:2016-02-14 13:37:56
【问题描述】:

我无法使用字符串键获取值

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

【问题讨论】:

  • 你确定只有027410。该字符串可能包含空字符 \0 但它不会出现
  • 您在代码中使用dateDic。稍后您参考stockShcodeDic["027410"] 可以。那些字典是一样的吗?
  • 显然字典中没有_code。当您遇到异常时,请在 Watch window _code == "027410" 尝试。
  • 在观察窗口,code == "027410" 是假的我发现我的错误

标签: c# dictionary keynotfoundexception


【解决方案1】:

字典中不存在该键,您可以使用 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>();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-10
    • 2012-08-20
    相关资源
    最近更新 更多