LINQ: Get all pairs from a dictionary where pair.key is in a string array

Viewed 518

Can someone help me translate this to LINQ? I have a string array (step.Variables), a dictionary (Parameters) and I want all pairs in Parameters where the key is in step.Variables.

This code works but I want to use LINQ and I cannot figure out how to translate:

parameters = new Dictionary<string, string>();
foreach (string variable in step.Variables)
{
    if (Parameters.ContainsKey(variable))
    {
        parameters[variable] = Parameters[variable];
    }
}

This is my best guess but get exeption:

var parameters = Parameters.ToDictionary(pair => step.Variables.Contains(pair.Key.ToString())).Select(pair => pair);

"System.ArgumentException: 'An item with the same key has already been added.'":
2 Answers

If I understand well, what you need is this:

var parameters = Parameters.Where(p=>step.Variables.Contains(p.Key))
                           .ToDictionary(p=>p.Key,p.Value); 

You need to filter first the Parameter dictionary to see if the key is in the Variables collection and convert the result, which is IEnumerable<KeyValuePair<string, string>>, into a Dictionary<string, string>

Filter out the Parameters dictionary if key exists in step.Variables then transform it to Dictionary.

var parameters = Parameters.Where(p => steps.Variables.Contains(p.Key)).ToDictionary(p => p.Key);
Related