gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 03:27:35 25 4
gpt4 key购买 nike

我正在使用 Exchange Web Services Managed API 和联系人数据。我有以下代码,它功能,但并不理想:

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
The given key was not present in the dictionary.

我怎样才能重构这段代码以减少(同时仍然起作用)?

最佳答案

您可以使用 ContainsKey :

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

TryGetValue :

dict.TryGetValue(key, out value);

更新:根据评论,这里的实际类不是IDictionary,而是PhysicalAddressDictionary。 , 所以方法是 ContainsTryGetValue但它们的工作方式相同。

示例用法:

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

...根据需要为每个所需的键重复内部条件。 TryGetValue 仅针对每个 PhysicalAddressKey(家庭、工作等)执行一次。

关于c# - 如何检测此字典键是否存在于 C# 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2829873/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com