Search code examples
c#dictionarykeynotfoundexception

KeyNotFoundException at dictionary with string key


I failed to get value 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>();
}

variable _code is 027410

At watch window:

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


Solution

  • The key is not present in the dictionary, you can handle it by using 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>();;
    

    or even simpler

    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>();
    }