2016-02-14 54 views
0

我失敗,串鍵KeyNotFoundException在字典中的字符串鍵

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

變量_code獲得價值027410

在監視窗口:

stockShcodeDic [_CODE] System.Collections中。 Generic.KeyNotFoundException < =錯誤 stockShcodeDic [「027410」] {Base.Data} Base.Data < = OK

+5

你肯定只有'027410'。該字符串可能包含空字符'\ 0',但它不會出現 –

+5

您正在代碼中使用'dateDic'。稍後你可以參考stockShcodeDic [「027410」]。這些字典是一樣的嗎? –

+1

顯然字典中缺少'_code'。當出現異常時,請在Watch窗口'_code ==「027410」'處嘗試。 –

回答

3

的關鍵是不存在的字典,你可以通過使用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>(); 
} 
相關問題