c# - Difference between two lists -


i have 2 generic list filled customsobjects.

i need retrieve difference between 2 lists(items in first without items in second one) in third one.

i thinking using .except() idea don't see how use this.. help!

using except right way go. if type overrides equals , gethashcode, or you're interested in reference type equality (i.e. 2 references "equal" if refer exact same object), can use:

var list3 = list1.except(list2).tolist(); 

if need express custom idea of equality, e.g. id, you'll need implement iequalitycomparer<t>. example:

public class idcomparer : iequalitycomparer<customobject> {     public int gethashcode(customobject co)     {         if (co == null)         {             return 0;         }         return co.id.gethashcode();     }      public bool equals(customobject x1, customobject x2)     {         if (object.referenceequals(x1, x2))         {             return true;         }         if (object.referenceequals(x1, null) ||             object.referenceequals(x2, null))         {             return false;         }         return x1.id == x2.id;     } } 

then use:

var list3 = list1.except(list2, new idcomparer()).tolist(); 

edit: noted in comments, remove duplicate elements; if need duplicates preserved, let know... easiest create set list2 , use like:

var list3 = list1.where(x => !set2.contains(x)).tolist(); 

Comments

Popular posts from this blog

php - What is the difference between $_SERVER['PATH_INFO'] and $_SERVER['ORIG_PATH_INFO']? -

fortran - Function return type mismatch -

queue - mq_receive: message too long -