How can I detect if this dictionary key exists in C#?

后端 未结 5 443
青春惊慌失措
青春惊慌失措 2020-11-30 17:51

I am working with the Exchange Web Services Managed API, with contact data. I have the following code, which is functional, but not ideal:

foreach (         


        
5条回答
  •  孤独总比滥情好
    2020-11-30 18:28

    You can use ContainsKey:

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

    or TryGetValue:

    dict.TryGetValue(key, out value);
    

    Update: according to a comment the actual class here is not an IDictionary but a PhysicalAddressDictionary, so the methods are Contains and TryGetValue but they work in the same way.

    Example usage:

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

    Update 2: here is the working code (compiled by question asker)

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

    ...with the inner conditional repeated as necessary for each key required. The TryGetValue is only done once per PhysicalAddressKey (Home, Work, etc).

提交回复
热议问题