【发布时间】:2016-03-25 11:46:02
【问题描述】:
我在 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);
}
}
【问题讨论】:
-
我认为你的想法是对的。看起来您只是将嵌套的
Joins 传递了错误的参数!例如,在Maps加入中,您尝试加入coreServer.Maps和oImportList... 我怀疑这应该是coreServer.Maps和importServer.Maps。 -
我能够在您的帮助下获得代码,但后来我发现结果不是我想要的列表。它只包含两个列表中都存在的元素。
-
啊,抱歉...我很少使用
Join,所以我把它弄混了。我使用GroupBy和Select取消删除了可能对您有用的答案。我之前删除了它,因为我认为我走错了路。