praveen1981
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.
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
Is this the right way , or will have any impact on performance, if so what is the right way , please guide me.
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;
}
}
https://msdn.microsoft.com/en-us/library/vstudio/bb300779(v=vs.100).aspx
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
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
ASKER
Hi Michael74
Is there any way in linq to achieve my task.
Is there any way in linq to achieve my task.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Thanks.
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