【发布时间】:2015-08-31 16:57:59
【问题描述】:
我有两个“伪类型”Hash(int key, list values) 对象,我需要根据键将它们合并为一个。例如,
[{1, {a, b, c}},
{2, {apple, pear}},
{3, {blue, red}}]
和
[{2, {tomato}},
{3, {pink, red}},
{4, {x, y, z}}]
我需要的结果是:
[{1, {a, b, c}},
{2, {apple, pear, tomato}},
{3, {blue, red, pink, red}},
{4, {x, y, z}}]
(类似 JSON 的格式是为了便于阅读)
我可以在服务器 (C#) 或客户端 (Javascript/Angular) 上执行此操作。 C# 中是否有一个聚合类型有一个方法可以做到这一点?或者也许是一些能做同样事情的高超的 LINQ 表达式?
或者最好的方法是让他们成为Hashtable<int, List<object>>,然后“手动”加入他们?
更新:根据下面的答案,这是提出问题的更好方法:
Dictionary<int, string[]> Dict1 = new Dictionary<int, string[]>();
Dict1.Add(1, new string[] { "a", "b", "c" });
Dict1.Add(2, new string[] { "apple", "pear" });
Dict1.Add(3, new string[] { "blue", "red" });
Dictionary<int, string[]> Dict2 = new Dictionary<int, string[]>();
Dict2.Add(2, new string[] { "tomato" });
Dict2.Add(3, new string[] { "pink", "red" });
Dict2.Add(4, new string[] { "x", "y", "z" });
foreach (var item in Dict2) {
if (Dict1.ContainsKey(item.Key)) {
Dict1[item.Key] = Dict1[item.Key].Concat(item.Value).ToArray();
} else {
Dict1.Add(item.Key, item.Value);
}
}
是否有一些 Collection 类型可以让我加入两个对象而不是通过循环?
【问题讨论】:
-
{a, b, c}是什么意思?它应该是[a,b,c]的数组吗?或者你的意思是 a 有对象 {a: somevalue, b: somevalue, c: somevalue } -
是的,我应该放 [] (我从
object[] x = new object[] {a, b, c}剪切和粘贴。但如果有限制,我可以做任何一种方式......
标签: javascript c# linq collections