如何将具有唯一键的字典列表转换为值为列表的字典?
我有任意数量的字典(它们在列表中,已经按顺序排列),我希望将其外部连接。例如,对于 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);
每个字典已经具有唯一的键。
我希望将 lstInput
转换为:
Dictionary<string, int[]> dctOutput = new Dictionary<string, int[]>();
其中 dctOutput
看起来像:
"ABC": [123, 321]
"CBA": [0, 321]
也就是说,dctOutput
的键集等于该集的并集lstInput
中每个字典的键;此外,dctOutput
中每个值的第 *i* 个位置等于 lstInput
中第 *i* 个字典中对应键的值,或 0
如果没有对应的键。
我如何编写 C# 代码来完成此任务?
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": [123, 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
以下应该做你想做的事。
这是可行的,因为分配数组会将所有值初始化为 0。因此,如果先前的字典没有包含该键的项目,则该位置的值将为 0。如果您希望哨兵值不是 0,那么您可以在分配数组后使用该值初始化该数组。
The following should do what you want.
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.