c# - Can I use LINQ to compare what is missing, added or updated between two collections -


i have following class. make compare added equals method:

 public objectivedetail()     public int objectivedetailid { get; set; }     public int number { get; set; }     public string text { get; set; }     public override bool equals(object obj)     {         return this.equals(obj objectivedetail);     }     public bool equals(objectivedetail other)     {         if (other == null)             return false;          return this.number.equals(other.number) &&             (                 this.text == other.text ||                 this.text != null &&                 this.text.equals(other.text)             );     }  } 

i have 2 icollection collections:

icollection<objectivedetail> _obj1; // reference icollection<objectivedetail> _obj2; // may have more, less or different objectdetails reference. 

the common tfield collections objectivedetailid. there way can use 3 linq expressions create:

  • a collection of rows in _obj2 , not _obj1
  • a collection of rows in _obj1 , not _obj2
  • a collection of rows different between _obj1 , _obj2

note similar question asked earlier think bit simpler have added equals method. uld this?

you can use except subtract sets:

var in2butnot1 = _obj2.except(_obj1); var in1butnot2 = _obj1.except(_obj2); 

however, may not looking get, because objects have "changed" treated "not equal" each other.

it appears objects have id field. can order objects on id, , traverse both collections if producing merge. let detect insertions, updates, , deletions straightforward chain of ifs.

you can use ids decide what's common , what's changed:

var ids1 = new hashset<int>(_obj1.select(o => o.objectivedetailid)); var ids2 = new hashset<int>(_obj2.select(o => o.objectivedetailid)); var in2butnot1 = _obj2.where(o => !ids1.contains(o.objectivedetailid)); var in1butnot2 = _obj1.where(o => !ids2.contains(o.objectivedetailid)); 

Comments

Popular posts from this blog

css - Which browser returns the correct result for getBoundingClientRect of an SVG element? -

gcc - Calling fftR4() in c from assembly -

.htaccess - Matching full URL in RewriteCond -