HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpModerate

Extracting values from dictionaries where the keys match

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
thewherematchkeysextractingvaluesdictionariesfrom

Problem

I have two Dictionaries with around 65,000 KeyValuePairs each. I used foreach and if-else statements to compare them and get values, but it goes very slow. How could I optimize my code and gain more speed?

private void bgwCompare_DoWork(object sender, DoWorkEventArgs e)
{
    var i = 0;

    foreach (KeyValuePair line1 in FirstDictionary)
    {
        foreach (KeyValuePair line2 in SecondDictionary)
        {
            if (line1.Key == line2.Key)
            {
                ResultDictionary.TryAdd(line1.Value, line2.Value);

                ListViewItem item = new ListViewItem(line1.Value);
                item.SubItems.Add(line2.Value);

                ResultList.Items.Add(item);
            }

            i++;
            bgwCompare.ReportProgress(i * 100 / (FirstDictionary.Count() * SecondDictionary.Count()));
        }
    }
}

Solution

If I'm understanding it correctly, you're populating a ConcurrentDictionary from the values of two other ConcurrentDictionaries, where the keys are equal.

Try this, it's vastly faster than your loop in my tests.

var matches = FirstDictionary.Keys.Intersect(SecondDictionary.Keys);
foreach (var m in matches)
    ResultDictionary.TryAdd(FirstDictionary[m], SecondDictionary[m]);

Code Snippets

var matches = FirstDictionary.Keys.Intersect(SecondDictionary.Keys);
foreach (var m in matches)
    ResultDictionary.TryAdd(FirstDictionary[m], SecondDictionary[m]);

Context

StackExchange Code Review Q#127210, answer score: 10

Revisions (0)

No revisions yet.