0

I have this code snippet and I need to check the dictionary before accessing it.

How can I verify the existence of the key before trying to access it ?

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;
                }
            }
Dolla
  • 27
  • 6

1 Answers1

1

You can either use the ContainsKey method or try to retrieve the value associated to the key:

if (links.TryGetValue(publication.PublicationId, out LinkCollection links))
{
    ...
}

(assuming links is a Dictionary<string, LinkCollection> for instance)

vc 74
  • 37,131
  • 7
  • 73
  • 89
  • Or out var then you don’t have to assume anything :) – Rand Random Mar 19 '21 at 18:17
  • In my case the "links" is an ILookup. In that case can I use Contains ()? – Dolla Mar 19 '21 at 18:33
  • 1
    @Dolla then you can use `Contains` instead of `ContainsKey`, but `TryGetValue` is not available. It's not an issue since `links[publication.PublicationId]` will return an empty enumerable in case the key is not present in the lookup, which emptiness can easily be detected with Linq's `Any`. – vc 74 Mar 19 '21 at 19:25