【发布时间】:2026-01-25 10:15:01
【问题描述】:
我有这个代码 sn-p,我需要在访问它之前检查字典。
如何在尝试访问之前验证密钥的存在?
foreach (var publication in publications)
{
var publicationLinks = links[publication.PublicationId];
var litigationLink = publicationLinks.FirstOrDefault(x => x.ProcessoId.HasValue);
if (litigationLink != null)
{
litigationLinks[publication.PublicationId] = litigationLink.ProcessoId.Value;
continue;
}
var contactLink = publicationLinks.FirstOrDefault(x => x.ContatoId.HasValue);
if (contactLink != null)
{
contactsLinks[publication.PublicationId] = contactLink.ContatoId.Value;
}
}
【问题讨论】:
-
使用 ContainsKey() 方法。
-
我更喜欢 TryGetValue 而不是 ContainsKey。 ContainsKey 让您重复内容。最终看起来像 PHP 中的东西
-
@JoelFan
ContainsKey+[]与TryGetValue相比也有性能影响 -
在我的例子中,“链接”是一个 ILookup。在那种情况下我可以使用 Contains () 吗?
标签: c# .net dictionary