logo CodeStepByStep logo

CollectionMystery5

Language/Type: C# collection mystery collections

Write the output that is printed when the given method below is passed each of the following dictionaries and lists as its parameters. Recall that dictionaries print in a {{key1, value1}, {key2, value2}, ..., {keyN, valueN}} format.

Though dictionaries usually have unpredictable ordering, for this problem, you should assume that when looping over the dictionary or printing a dictionary, it visits the keys in the order that they were added to the dictionary in the order they are declared below. If a dictionary adds a key that already exists, it retains its current position in the ordering.

public static void CollectionMystery5(List<string> list1, List<string> list2)
{
    Dictionary<string, string> result = new Dictionary<string, string>();
    for (int i = 0; i < list1.Count; i++)
    {
        string s1 = list1[i];
        string s2 = list2[i];

        if (!result.ContainsKey(s1))
        {
            result[s1] = s2;
        }
        else if (!result.ContainsKey(s2))
        {
            result[s2] = s1;
        }
        else
        {
            result[s1 + s2] = s1;
        }
    }
    Console.WriteLine(result);
}
list1 = {"cat", "cat", "long", "long", "longcat"} list2 = {"mew", "purr", "cat", "cat", "purr"}
list1 = {"a", "b", "a", "ab", "ab", "y", "abb"} list2 = {"b", "c", "b", "b", "c", "abb", "y"}

You must log in before you can solve this problem.

Log In

Need help?

If you do not understand how to solve an exercise or why your solution doesn't work, please contact your TA or instructor.
If something seems wrong with the site (errors, slow performance, incorrect tests, etc.), please

Is there a problem? Contact a site administrator.

©, all rights reserved.