【发布时间】:2015-04-09 22:38:13
【问题描述】:
我看到了Quickest way to compare two List<>,但我无法适应我的情况。我的问题是列表的类型不同。
我的列表是这样的:
List<Type1> firstList;
List<Type2> secondList;
这是我现在拥有的:
foreach (Type1 item in firstList)
{
if (!secondList.Any(x => x.Id == item.Id))
{
// this code is executed on each item in firstList but not in secondList
}
}
foreach (Type2 item in secondList)
{
if (!firstList.Any(x => x.Id == item.Id))
{
// this code is executed on each item in secondList but not in firstList
}
}
这一切正常,但它是O(n^2)。有没有办法让这更有效?我在上面链接的问题中的解决方案是使用.Except,但它不需要 lambda。
编辑: 我在上面提到了这一点,但这仍然被标记为重复。我没有两个相同对象的列表。我有两个不同对象的列表。 Type1 和 Type2 是不同的类型。他们只是都有一个我需要匹配的 id。
【问题讨论】:
-
不是真的,因为他只是在比较 id
-
Id...不是属性吗?
-
怎么是重复的?您标记的问题是比较两个 MyObject 列表。我没有两个相同类型的列表。我有一个 Type1 和 Type2,它们都只有一个我需要匹配的 Id。如果它在 firstList 但不在 secondList 中,如果它在 secondList 但不在 firstList 中,我需要做不同的事情。所以基本上我需要两个部分说
//do something here。