All rules
CA1841Performance Enabled by default: As suggestion

Prefer Dictionary Contains methods

Prefer Dictionary Contains methods

Microsoft docs

Description

Calling Contains on the Keys or Values collection can often be more expensive than calling ContainsKey or ContainsValue on the dictionary itself:

  • Many dictionary implementations lazily instantiate the key and value collections, which means that accessing the Keys or Values collection may result in extra allocations.
  • You may end up calling an extension method on System.Collections.Generic.IEnumerable1 if the keys or values collection uses explicit interface implementation to hide methods on System.Collections.Generic.ICollection1. This can lead to reduced performance, especially when accessing the key collection. Most dictionary implementations are able to provide a fast O(1) containment check for keys, while the Contains extension method on System.Collections.Generic.IEnumerable`1 usually does a slow O(n) containment check.

Cause

This rule locates calls to a Contains method on the Keys or Values collection of an System.Collections.Generic.IDictionary2 that could be replaced with a call to a ContainsKey or ContainsValue` method on the dictionary itself.

How to fix violations

To fix violations, replace calls to dictionary.Keys.Contains or dictionary.Values.Contains with calls to dictionary.ContainsKey or dictionary.ContainsValue, respectively.

The following code snippet shows examples of violations, and how to fix them.

Example

using System.Collections.Generic;
// Importing this namespace brings extension methods for IEnumerable<T> into scope.
using System.Linq;

class Example
{
    void Method()
    {
        var dictionary = new Dictionary<string, int>();

        //  Violation
        dictionary.Keys.Contains("hello world");

        //  Fixed
        dictionary.ContainsKey("hello world");

        //  Violation
        dictionary.Values.Contains(17);

        //  Fixed
        dictionary.ContainsValue(17);
    }
}

When to suppress

It is safe to suppress warnings from this rule if the code in question is not performance-critical.

Group results
0 yes 0 no
ConsensusNone (disabled)
Severity preference (yes voters)
Suggestion0
Warning0
Error0