I saw 比较两个 List 的最快方法 https://stackoverflow.com/questions/12795882/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。
我建议将 2 种类型的 Id 转换为 2 个 HashSet。然后你可以
HashSet<int> a = new HashSet<int>(firstList.Select(o => o.Id));
HashSet<int> b = new HashSet<int>(secondList.Select(o => o.Id));
if (a.IsSubsetOf(b) && b.IsSubsetOf(a))
{
//Do your thing
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)