开发者

How to transform a list of dictionaries with unique keys to a dictionary whose value is a list?

开发者 https://www.devze.com 2023-04-13 00:36 出处:网络
I have an arbitrary number of dictionaries (which are in a list, already in order) that I wish to outer join. For example, for N = 2:

I have an arbitrary number of dictionaries (which are in a list, already in order) that I wish to outer join. For example, for N = 2:

List<Dictionary<string, int>> lstInput = new List<Dictionary<string, int>>();
Dictionary<string, int> dctTest1 = new Dictionary<string, int>();
Dictionary<string, int> dctTest2 = new Dictionary<string, int>();
dctTest1.Add("ABC", 123);
dctTest2.Add("ABC", 321);
dctTest2.Add("CBA", 321);
lstInput.Add(dctTest1);
lstInput.Add(dctTest2);

Each dictionary already has unique keys.

I wish to transform lstInput into:

Dictionary<string, int[]> dctOutput = new Dictionary<string, int[]>();

where dctOutput looks like:

"ABC": [12开发者_StackOverflow社区3, 321]
"CBA": [0, 321]

That is, the set of keys of dctOutput is equal to the union of the set of keys of each dictionary in lstInput; moreover, the *i*th position of each value in dctOutput is equal to the value of the corresponding key in the *i*th dictionary in lstInput, or 0 if there is no corresponding key.

How can I write C# code to accomplish this?


The following should do what you want.

var dctOutput = new Dictionary<string, int[]>();
for (int i = 0; i < lstInput.Count; ++i)
{
    var dict = lstInput[i];
    foreach (var kvp in dict)
    {
        int[] values;
        if (!dctOutput.TryGetValue(kvp.Key, out values))
        {
            // Allocating the array zeros the values
            values = new int[lstInput.Count];
            dctOutput.Add(kvp.Key, values);
        }
        values[i] = kvp.Value;
    }
}

This works because allocating the array initializes all values to 0. So if a previous dictionary didn't have an item with that key, its values will be 0 in that position. If you wanted your sentinel value to be something other than 0, then you would initialize the array with that value after allocating it.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号