C # Comparing two lists of different objects

I saw the fastest way to compare two lists <> , but I find it difficult to adapt it to my situation. My problem is that lists have different types.

My lists are as follows:

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

It works and that’s all, but O(n^2). Is there a way to make this more efficient? The solution to the above issues says to use .Except, but does not accept lambda.

Edit: I mentioned this above, but it is still marked 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 have an identifier that I need to map.

0
3

2 HashSets.

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

Except - , IEqualityComparer<T>.

MSDN : https://msdn.microsoft.com/en-us/library/bb336390.aspx


IEqualityComparer<T>. :

class MyEqualityComparer : IEqualityComparer<object>
{
    #region IEqualityComparer<object> Members

    bool IEqualityComparer<object>.Equals(object x, object y)
    {
        return (x as dynamic).Id == (y as dynamic).Id;
    }

    int IEqualityComparer<object>.GetHashCode(object obj)
    {
        return ((obj as dynamic).Id as object).GetHashCode();
    }

    #endregion
}

LINQ :

var result = lst1.Select(x => new { Id = x.Id, Obj = x })
    .Except(lst2.Select(x => new { Id = x.Id, Obj = x }),
            new MyEqualityComparer())
    .Select(x => (x as dynamic).Obj as Type1);

, , .

0

I am not sure about the available C # / Linq methods. From an algorithmic point of view, you can sort both lists (usually O(n*log(n))). Then you just need to scan the lists (linear, aka O(m+n), where mis the number of elements in list 1 and the nnumber of elements in list 2). Assuming list 1 is longer, overall complexity O(m*log(m)). Depending on the C # HashSet implementation, Murdock's answer might be faster though.

0
source

Source: https://habr.com/ru/post/1671574/


All Articles