C#中字典中的KeyNotFoundException

时间:2012-05-17 18:42:30

标签: c# .net dictionary

我在这里有点困惑。我收到这个异常,告诉我这个密钥不存在。当我在观察窗口中查看字典中的所有键/值对时,问题的关键在于!!!我不认为我会发疯,但我可能会。我在这里错过了什么吗?这是代码:

public static List<Quote> GetQuoteHistory(int id)
{
    List<Quote> quotes = DataAccess.GetQuoteHistory(id);
    SetAckCodeDescriptions(quotes);
    return quotes;
}

private static void SetAckCodeDescriptions(IEnumerable<Quote> quotes)
{
    Dictionary<string, string> ackData = GetAcknowlegementData();

    foreach (Quote quote in quotes)
    {
        quote.AckCodes = GetAckCodeHtml(quote.AckCodes, ackData);
    }
}

private static string GetAckCodeHtml(string ackCodes, IDictionary<string, string> ackData)
{
    string[] codes = ackCodes.Split(',');

    string html = string.Empty;
    foreach (string code in codes)
    {
        html += string.Format("<div title='#= {0} #'>#= {1} #</div>, ", ackData[code], code);
    }

    return html.TrimEnd(new []{',', ' '}); // remove extra comma and space
}

更新

public static Dictionary<string, string> GetAcknowlegementData()
{
    List<AckData> list = DataAccess.GetAcknowlegementData();
    return list.ToDictionary(o => o.AcknowledgementCode, o => o.Description);
}

1 个答案:

答案 0 :(得分:2)

尝试迭代字典中的值/对。看看你是否真的有这个元素(眼睛可以撒谎)。

foreach (var pair in ackData)
{
    Console.WriteLine("{0},{1}", pair.Key, pair.Value);
}