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])


alternative non linq answer:

decimal total = 0;
foreach (var car in selectedlist)
    total += cars[car];


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

var sum = selectedlist
            .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.


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);

Related Query

More Query from same tag