Get keys and values ​​from the dictionary, except for & ldquo; Foreach & ldquo;

advertisements

i have:

Dictionary<string, Dictionary<string, string>> matchesLists = new Dictionary<string, Dictionary<string, string>>();
if (matchesLists.ContainsKey("Errors"))
{
    var dict = GetInnerTextMatches(webDriver);
    dict.Keys.ToList().ForEach(k => matchesLists["Errors"].Add(k, dict[k]));
}
else
    matchesLists.Add("Errors", GetInnerTextMatches(webDriver));

GetInnerTextMatches(webDriver) returns Dictionary<string,string>

whether there is an easier way to add dictionary to matchesLists["Errors"]?


Currently you're adding to an existing dictionary which has been returned by something else. I wouldn't do that - it ends up causing potentially confusing behaviour. I'd write that code as this:

Dictionary<string, string> errors;
if (!matchesLists.TryGetValue("Errors", out errors))
{
    errors = new Dictionary<string, string>();
    matchesLists["Errors"] = errors;
}
foreach (var entry in GetInnerTextMatches(webDriver))
{
    errors.Add(entry.Key, entry.Value);
}

That way you know that however GetInnerTextMatches is implemented, it doesn't matter - you're not going to interfere with it, and any internal changes to the dictionary returned by it won't interfere with you either.