Well, depending on the number of dictionaries in Foo may be an advantage when using Parallel LINQ (PLINQ):
string name = null; Parallel.ForEach(foo, f => { if (name != null) return; if (f.ContainsKey(key)) name = f[key]; });
The implementation assumes that the given key is mapped to the same value or that the key is unique in all dictionaries. It is also assumed that the value is not equal to zero.
With 5,000,000 dictionaries containing one key and one value, this works about 150 ms faster than your original implementation.
Benchmarks (Intel Core i5 with a clock frequency of 2.4 GHz with two physical cores and two virtual cores):
- PLINQ: 89ms
- Initial Solution: 250 ms
However, I want to emphasize that PLINQ is not always the answer to getting things to work faster. In some cases, when you have code that uses parallel foreach loops to move multiple elements, the actual cost of starting threads in the background is actually much more expensive than just repeating using a simple for loop - so use it when there is a lot elements to iterate through :)
source share