C#比较两个不同对象的列表 [英] C# Compare Two Lists of Different Objects

查看:493
本文介绍了C#比较两个不同对象的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到了比较两个列表的最快方法,但是我无法适应我的情况.我的问题是列表的类型不同.

I saw Quickest way to compare two List<> but I'm having trouble adapting it to my situation. My issue is that the lists are of different types.

我的列表如下:

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.

This works and all, but is O(n^2). Is there a way to make this more efficient? The solution in the questions I linked above says to use .Except but it doesn't take a lambda.

我在上面提到了这一点,但仍被标记为重复.我没有同一对象的两个列表.我有两个不同对象的列表. Type1和Type2是不同的类型.他们两个都有一个我需要匹配的ID.

I mentioned this above, but this is still being flagged as duplicate. I DO NOT have two lists of the same object. I have two lists of different objects. Type1 and Type2 are different types. They just both have an id that I need to match on.

推荐答案

我建议将2种类型的ID转换为2个HashSet.然后你可以

I would recommend converting the Ids of the 2 types to 2 HashSets. Then you can

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
}

这篇关于C#比较两个不同对象的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆