我有两个C#列表,其结构如下。<>中的每个名称都是一个列表。我想将这两个列表合并成一个List<Server>
。以下伪代码显示了两个这样的列表以及结果应该是什么:
<Servers> <Servers>
+... +...
+-- Server A,1 +-- Server A,1
| +... | +...
| +--<Maps> | +--<Maps>
| +--Map x | +--Map x
| +... | +...
| +--<Times> | +--<Times>
| +--Time i | +--Time l
| +--Time j | +--<Jumps>
| +--<Jumps> | +--Jump t
| +--Jump s | +--Jump u
| +--Map y | +--Map z
| +... | +...
| +--<Times> | +--<Jumps>
| +-- Time k | +--Jump v
+-- Server B,1 +-- Server B,2
结果应该如下:
<Servers>
+...
+-- Server A,1
| +...
| +--<Maps>
| +-- Map x
| +...
| +--<Times>
| +--Time i
| +--Time j
| +--Time l
| +--<Jumps>
| +--Jump s
| +--Jump t
| +--Jump u
| +-- Map y
| +...
| +--<Times>
| +--Time k
| +-- Map z
| +...
| +--<Jumps>
| +--Jump v
+-- Server B,1
+-- Server B,2
我尝试使用LINQ进行全外连接,但结果并不是我想要的。由于我不理解相同键值的服务器没有匹配,因此我总是得到具有不同数据的相同服务器的重复项。那时,我停止了使用LINQ,并使用循环手动合并列表。
下面的代码给了我所需的结果列表。目前我将使用它,直到我找到更好的方法。是否有使用LINQ或Lambda表达式更简单/更短的方法呢?
foreach (Server importServer in oImportList)
{
if (!CoreList.Contains(importServer))
{
CoreList.Add(importServer);
continue;
}
Server coreServer = CoreList.FirstOrDefault(o => o.Equals(importServer));
coreServer.Name = importServer.Name;
coreServer.KZTimerVersion = importServer.KZTimerVersion;
foreach(Map importMap in importServer.Maps)
{
if (!coreServer.Maps.Contains(importMap))
{
coreServer.Maps.Add(importMap);
continue;
}
Map coreMap = coreServer.Maps.FirstOrDefault(o => o.Equals(importMap));
coreMap.Jumps.Concat(importMap.Jumps);
coreMap.Times.Concat(importMap.Times);
}
}
Join
!例如,在Maps
连接中,你试图连接coreServer.Maps
和oImportList
... 我猜这应该是coreServer.Maps
和importServer.Maps
。 - 31eee384Join
,所以搞混了。我恢复了一个使用GroupBy
和Select
的答案,也许适合你。之前我删除它是因为我觉得我走错了方向。 - 31eee384