C# Compare Two Lists of Different Objects

10,761

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
}
Share:
10,761
vkapadia
Author by

vkapadia

Updated on June 04, 2022

Comments

  • vkapadia
    vkapadia almost 2 years

    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.

    My lists are like this:

    List<Type1> firstList;
    List<Type2> secondList;
    

    Here is what I have now:

    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
        }
    }
    

    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.

    Edit: 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.