我有两个“伪类型”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 类型允许我连接两个对象而不是通过循环?
最佳答案
有几种方法可以实现这一点,我猜您想使用 json 文件作为源文件,那么为什么不将所有内容都转换为对象并以这种方式处理它们,这将为您提供更大的灵 active 操纵它们并在需要时执行更复杂的处理。
这是我的草稿:
using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main()
{
List<JsonModel> ListJson1 = new List<JsonModel>();
ListJson1.Add(new JsonModel(1, new List<string>(new string[] {"a", "b", "c"})));
ListJson1.Add(new JsonModel(2, new List<string>(new string[] {"apple", "pear"})));
ListJson1.Add(new JsonModel(3, new List<string>(new string[] {"blue", "red"})));
List<JsonModel> ListJson2 = new List<JsonModel>();
ListJson2.Add(new JsonModel(2, new List<string>(new string[] {"tomato"})));
ListJson2.Add(new JsonModel(3, new List<string>(new string[] {"pink", "red"})));
ListJson2.Add(new JsonModel(4, new List<string>(new string[] {"x", "y", "z"})));
List<JsonModel> result = ListJson1.Concat(ListJson2)
.ToLookup(p => p.Index)
.Select(g => g.Aggregate((p1,p2) =>
new JsonModel(p1.Index,p1.Names.Union(p2.Names)))).ToList();
foreach(var item in result)
{
Console.WriteLine(item.Index);
foreach(var Item in item.Names)
Console.WriteLine(Item);
}
}
}
public class JsonModel
{
public int Index;//you can use your private set and public get here
public IEnumerable<string> Names;//you can use your private set and public get here
public JsonModel(int index, IEnumerable<string> names)
{
Index = index;
Names = names;
}
}
output: 1 a b c 2 apple pear tomato 3 blue red pink 4 x y z
检查这个link出
关于javascript - 在 C# 或 JavaScript 中加入两个集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30858014/