Multiplying two dictionaries

Viewed 53

Is there a more optimal way to do the following -

int interactionScore = 0;

        foreach (var completionResult in needs.Keys.Intersect(results.Keys))
        {
            interactionScore -= results[completionResult] * needs[completionResult];
        }

both needs and results are small dictionaries (around 2 - 10 entries each) but the number of times I run this loop is very high and it is hurting my performance, so I was wondering if there is a more efficient way to achieve similar results (multiplying only entries which exist in both dictionaries).

1 Answers

Avoid Intersect

int interactionScore = 0;
foreach (var key in needs.Keys)
{
  if (results.TryGetValue(key, out int result))
  {
    int need = needs[key];
    interactionScore -= result * need;
  }
}
Related