代码之家  ›  专栏  ›  技术社区  ›  Adam Tuttle

如何检测C#中是否存在此字典键?

  •  391
  • Adam Tuttle  · 技术社区  · 16 年前

    功能性 ,但不理想:

    foreach (Contact c in contactList)
    {
        string openItemUrl = "https://" + service.Url.Host + "/owa/" + c.WebClientReadFormQueryString;
    
        row = table.NewRow();
        row["FileAs"] = c.FileAs;
        row["GivenName"] = c.GivenName;
        row["Surname"] = c.Surname;
        row["CompanyName"] = c.CompanyName;
        row["Link"] = openItemUrl;
    
        //home address
        try { row["HomeStreet"] = c.PhysicalAddresses[PhysicalAddressKey.Home].Street.ToString(); }
        catch (Exception e) { }
        try { row["HomeCity"] = c.PhysicalAddresses[PhysicalAddressKey.Home].City.ToString(); }
        catch (Exception e) { }
        try { row["HomeState"] = c.PhysicalAddresses[PhysicalAddressKey.Home].State.ToString(); }
        catch (Exception e) { }
        try { row["HomeZip"] = c.PhysicalAddresses[PhysicalAddressKey.Home].PostalCode.ToString(); }
        catch (Exception e) { }
        try { row["HomeCountry"] = c.PhysicalAddresses[PhysicalAddressKey.Home].CountryOrRegion.ToString(); }
        catch (Exception e) { }
    
        //and so on for all kinds of other contact-related fields...
    }
    

    就像我说的,这个密码 作品 . 现在我想让它变得很糟糕 少一点 ,如果可能的话。

    我找不到任何方法允许我在尝试访问字典之前检查字典中是否存在键,如果我尝试读取它(使用 .ToString()

    500
    词典中没有给定的键。

    如何重构这段代码以减少代码的消耗(同时保持功能性)?

    5 回复  |  直到 12 年前
        1
  •  985
  •   Adam Tuttle    16 年前

    你可以用 ContainsKey :

    if (dict.ContainsKey(key)) { ... }
    

    或 TryGetValue :

    dict.TryGetValue(key, out value);
    

    更新 IDictionary 但是 PhysicalAddressDictionary Contains 和 TryGetValue

    PhysicalAddressEntry entry;
    PhysicalAddressKey key = c.PhysicalAddresses[PhysicalAddressKey.Home].Street;
    if (c.PhysicalAddresses.TryGetValue(key, out entry))
    {
        row["HomeStreet"] = entry;
    }
    

    更新2:

    PhysicalAddressEntry entry;
    PhysicalAddressKey key = PhysicalAddressKey.Home;
    if (c.PhysicalAddresses.TryGetValue(key, out entry))
    {
        if (entry.Street != null)
        {
            row["HomeStreet"] = entry.Street.ToString();
        }
    }
    

        2
  •  13
  •   John Saunders    16 年前

    这是什么类型的 c.PhysicalAddresses ? 如果是的话 Dictionary<TKey,TValue> ContainsKey

        3
  •  5
  •   David Neale    16 年前

    PhysicalAddressDictionary.TryGetValue

     public bool TryGetValue (
        PhysicalAddressKey key,
        out PhysicalAddressEntry physicalAddress
         )
    
        4
  •  4
  •   JohanE    8 年前

     private static string GetKey(IReadOnlyDictionary<string, string> dictValues, string keyValue)
     {
         return dictValues.ContainsKey(keyValue) ? dictValues[keyValue] : "";
     }
    

    var entry = GetKey(dictList,"KeyValue1");
    

    完成任务。

        5
  •  1
  •   xul8tr    8 年前

    这是我今天做的一点小东西。似乎对我有用。基本上,您可以重写基命名空间中的Add方法来执行检查,然后调用基的Add方法来实际添加它。希望这对你有用

    using System;
    using System.Collections.Generic;
    using System.Collections;
    
    namespace Main
    {
        internal partial class Dictionary<TKey, TValue> : System.Collections.Generic.Dictionary<TKey, TValue>
        {
            internal new virtual void Add(TKey key, TValue value)
            {   
                if (!base.ContainsKey(key))
                {
                    base.Add(key, value);
                }
            }
        }
    
        internal partial class List<T> : System.Collections.Generic.List<T>
        {
            internal new virtual void Add(T item)
            {
                if (!base.Contains(item))
                {
                    base.Add(item);
                }
            }
        }
    
        public class Program
        {
            public static void Main()
            {
                Dictionary<int, string> dic = new Dictionary<int, string>();
                dic.Add(1,"b");
                dic.Add(1,"a");
                dic.Add(2,"c");
                dic.Add(1, "b");
                dic.Add(1, "a");
                dic.Add(2, "c");
    
                string val = "";
                dic.TryGetValue(1, out val);
    
                Console.WriteLine(val);
                Console.WriteLine(dic.Count.ToString());
    
    
                List<string> lst = new List<string>();
                lst.Add("b");
                lst.Add("a");
                lst.Add("c");
                lst.Add("b");
                lst.Add("a");
                lst.Add("c");
    
                Console.WriteLine(lst[2]);
                Console.WriteLine(lst.Count.ToString());
            }
        }
    }