score:11

Accepted answer

Just so:

var sum = selectedList.Sum(s=>cars[s]);

Or if you are not sure, that all values are in the dictionary (thanks Tim Schmelter for correction):

var sum = selectedList.Sum(s=>cars.ContainsKey(s)?cars[s]:0);

EDIT: Even better is from Tim proposed solution:

selectedList.Where(cars.ContainsKey).Sum(s => cars[s])

score:5

You could filter the items from the dictionary and then sum the values:

var sum = cars
    .Where(item => selectedList.Contains(item.Key))
    .Sum(item => item.Value);

score:0

Alternative non LINQ answer:

decimal total = 0;
foreach (var car in selectedList)
{
    total += cars[car];
}

score:1

So here's a different approach that might perform a bit better for some edge cases:

var sum = selectedList
            .Distinct()
            .Sum(s =>
            {
                decimal d;
                if (cars.TryGetValue(s, out d))
                {
                    return d;
                }
                return 0;
            }
        );

You only want distinct values from the list iterated, and this way you'll avoid duplicating lookups in the cars dictionary (if that's not the case, then just comment out the Distinct()). This should offer a good balance of performance regardless of whether the list or the dictionary are larger.


Related Articles