我怎样才能给字典中的空键

时间:2016-06-08 11:09:44

标签: c# dictionary

我该如何解决这个问题?

  

字典中没有给定的密钥

这是错误消息:

  

mscorlib.dll中发生未处理的“System.Collections.Generic.KeyNotFoundException”类型异常

     

附加信息:字典中没有给定的密钥

预览:http://i.stack.imgur.com/Acu1g.png

static void Main(string[] args)
    {

        HtmlWeb web = new HtmlWeb();
        string url = "http://linsa.softinsa.com/account/login";
        HtmlDocument document = web.Load(url);

        var head = document.DocumentNode.SelectSingleNode("//head");
        var meta = head.SelectNodes("//meta").AsEnumerable();
        var link = document.DocumentNode.SelectSingleNode("//head").SelectNodes("//link").AsEnumerable();

        var titulo = "" ;
        var descricao = "" ;
        var linkImg = "" ;
        var linkIcon = "" ;

        Uri myUri = new Uri(url);
        string host = myUri.Host;


        var fbProperties = (head.SelectNodes("//meta[contains(@property, 'og:')]") ?? Enumerable.Empty<HtmlNode>())
            .ToDictionary(n => n.Attributes["property"].Value, n => n.Attributes["content"].Value);

        linkIcon = (head.SelectSingleNode("//link[contains(@rel, 'apple-touch-icon')]")?.Attributes["href"]?.Value) ??
            (head.SelectSingleNode("//link[conntains((@rel, 'icon']")?.Attributes["href"]?.Value) ??
            host + "/favicon.ico";


        var title = head.SelectSingleNode("//title")?.InnerText;



        titulo = fbProperties["og:title"] ?? title ?? "";

        descricao = fbProperties["og:description"];

        linkImg = fbProperties["og:image"];


        Console.WriteLine("");
        Console.WriteLine("Titulo:");
        Console.WriteLine(titulo);
        Console.WriteLine("");
        Console.WriteLine("Descriçao:");
        Console.WriteLine(descricao);
        Console.WriteLine("");
        Console.WriteLine("Link da Imagem:");
        Console.WriteLine(linkImg);
        Console.WriteLine("");
        Console.WriteLine("Link do Icon:");
        Console.WriteLine(linkIcon);

        Console.ReadLine();
        }
    }
}

3 个答案:

答案 0 :(得分:0)

在尝试使用索引运算符将其删除之前,您需要使用TryGetValueContainsKey来检查字典中是否存在该键。

例如:

titulo = fbProperties["og:title"] ?? title ?? "";

变为:

if(fbProperties.TryGetValue("og:title", out titulo) == false || titulo == null)
{
  titulo = (title ?? "");
}

escricao = fbProperties["og:description"];

变为

fbProperties.TryGetValue("og:description", out descricao);

如果TryGetValue无法找到密钥,descricao会将null设置为ivory_ck_editor: enable: true autoload: false async: true base_path: bundles/ivoryckeditor/ js_path: bundles/ivoryckeditor/ckeditor.js default_config: ~ configs: my_config: toolbar: full uiColor: "#000000" extraPlugins: "wordcount" name: [] plugins: name: path: ~ filename: ~ styles: name: []

答案 1 :(得分:0)

如果您不知道它在那里,您应该使用

ContainsKeyif (fbProperties.ContainsKey("og:title")) { ... }

TryGetValuefbProperties.TryGetValue("og:title", out value);

答案 2 :(得分:0)

当您不确定字典中是否存在给定条目时,您应该使用TryGetValue() method。此方法返回truefalse以指示是否找到了给定的密钥,并且具有out参数用于在找到时返回值。 (注意,当在字典中找不到密钥时,out参数设置为其默认值)

请参阅以下示例,其中我已经调整了&#34;标题&#34;使用TryGetValue()方法:

if (fbProperties.TryGetValue("og:title", out titulo) == false)
{
    // Fall-back to "title" or an empty string when not found in dictionary
    titulo = title ?? "";
}