c# - Issue when trying to determine common elements in two List<T> -


i have class, called classx purposes of question, declared follows:

class x  {      public guid id { get; set; }      public string name { get; set; }      public string description { get; set; }  } 

if have 2 instances (instanceone , instancetwo) of list<t> of these classes, how can find elements same in both instances:

assume there 2 elements in instanceone , 4 elements in instancetwo. 2 of elements same (as defined fact have same guid id) in each of instances

i thought should able linq way isn't doing me

// what's common 2 instances? var commonelements = (     in instancetwo     join b in instanceone on a.id equals b.id     select b).tolist();  // what's not in instanceone , in instancetwo?  var notininstanceone = instancetwo.except(commonelements) 

in situation instancetwo superset of instanceone may not case should able flip original linq statement elements in instanceone not in instancetwo viz:

var notininstancetwo = instanceone.except(commonelements) 

frustratingly original linq statement (where attempt determine common elements) isn't working, can spot i'm doing wrong?

edit 2012-06-08 11:00 utc

per @nikhil agrawal , @trust me - i'm doctor have used intersect method doesn't produce expected results:

    var commonitems = instancetwo.intersect(instanceone); // returns nothing     var itemsintwonotone= instancetwo.except(instanceone); // returns in instancetwo 

fwiw implementation of equals() method is:

public bool equals(guid x, guid y) {    if (x == y)    {       return true;    }    return false; } 

use can use intersect list of common elements. should create iequalitycomparer, since want identify elements id.

example:

class program {     class x     {         public guid id { get; set; }         public string name { get; set; }         public string description { get; set; }     }      class xequalitycomparer : iequalitycomparer<x>     {         //note: maybe add null check in these methods         public bool equals(x x, x y) { return x.id.equals(y.id); }         public int gethashcode(x obj) { return obj.id.gethashcode(); }     }      static void main(string[] args)     {         var instanceone = new list<x>() {              new x() { id = guid.newguid() },              new x() { id = guid.parse("ef42ee32-1b9e-493c-9d39-4610e0fb29d0") }          };         var instancetwo = new list<x>() {              new x() { id = guid.newguid() },              new x() { id = guid.parse("ef42ee32-1b9e-493c-9d39-4610e0fb29d0") }          };          var common = instanceone.intersect(instancetwo, new xequalitycomparer());     } } 

Comments

Popular posts from this blog

django - How can I change user group without delete record -

java - Need to add SOAP security token -

java - EclipseLink JPA Object is not a known entity type -