Link to home
Start Free TrialLog in
Avatar of praveen1981
praveen1981Flag for India

asked on

Compare two different Lists

Hi ,

I have the following two classes with properties

Class ABC
{
 Property int code{get;set;}
Property string name {get;set;}
}
Class DEF
{
Property int code{get;set;}
Property string name {get;set;}
}

Now I have List< ABC> and List < DEF>
And I want to compare these two lists and get the values of DEF which is not present in ABC, I have used following code to achieve that
var matchedAccounts =
                    DEF.Where(x => ABC.Any(y => y.Code == x. Code)).ToList();

                var unMatchedAccounts = DEF.Except(matchedAccounts).ToList();

Is this the right way , or will have any impact on performance, if so what is the right way , please guide me.
Avatar of Rafiq J
Rafiq J
Flag of India image

Use Except to compare the two list: Think abc is list1 & cde is the List.

var firstNotSecond = list1.Except(list2).ToList();
var secondNotFirst = list2.Except(list1).ToList();

It works faster than

var list1 = list.Where(i => !list2.Contains(i)).ToList();
var list2 = list2.Where(i => !list.Contains(i)).ToList();



Like if it's works.
any doubt post your comments
To ensure that the objects compare correctly using either of the methods discussed you should also implement the IEquatable<T> generic interface.

Class ABC  : IEquatable<ABC>
{
 Property int code{get;set;}
Property string name {get;set;}

    public bool Equals(Product other)
    {
        if (Object.ReferenceEquals(other, null)) return false;
        if (Object.ReferenceEquals(this, other)) return true;
        return Code.Equals(other.Code) && Name.Equals(other.Name);
    }

    public override int GetHashCode()
    {
        int hashProductName = Name == null ? 0 : Name.GetHashCode();
        int hashProductCode = Code.GetHashCode();
        return hashProductName ^ hashProductCode;
    }
}

Open in new window

https://msdn.microsoft.com/en-us/library/vstudio/bb300779(v=vs.100).aspx
Avatar of praveen1981

ASKER

Hi Rafiq J,

I am talking about two different types(class objects), but it seems the answer which you have provided will work for the same type of objects in list
Hi Michael74

Is there any way in linq to achieve my task.
ASKER CERTIFIED SOLUTION
Avatar of Michael Fowler
Michael Fowler
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks.