Note that there are some explanatory texts on larger screens.

plurals
  1. PORemove repetitive, hard coded loops and conditions in C#
    text
    copied!<p>I have a class that compares 2 instances of the same objects, and generates a list of their differences. This is done by looping through the key collections and filling a set of other collections with a list of what has changed (this may make more sense after viewing the code below). This works, and generates an object that lets me know what exactly has been added and removed between the "old" object and the "new" one.<br> My question/concern is this...it is really ugly, with tons of loops and conditions. Is there a better way to store/approach this, without having to rely so heavily on endless groups of hard-coded conditions? </p> <pre><code> public void DiffSteps() { try { //Confirm that there are 2 populated objects to compare if (NewStep.Id != Guid.Empty &amp;&amp; SavedStep.Id != Guid.Empty) { //&lt;TODO&gt; Find a good way to compare quickly if the objects are exactly the same...hash? //Compare the StepDoc collections: OldDocs = SavedStep.StepDocs; NewDocs = NewStep.StepDocs; Collection&lt;StepDoc&gt; docstoDelete = new Collection&lt;StepDoc&gt;(); foreach (StepDoc oldDoc in OldDocs) { bool delete = false; foreach (StepDoc newDoc in NewDocs) { if (newDoc.DocId == oldDoc.DocId) { delete = true; } } if (delete) docstoDelete.Add(oldDoc); } foreach (StepDoc doc in docstoDelete) { OldDocs.Remove(doc); NewDocs.Remove(doc); } //Same loop(s) for StepUsers...omitted for brevity //This is a collection of users to delete; it is the collection //of users that has not changed. So, this collection also needs to be checked //to see if the permisssions (or any other future properties) have changed. foreach (StepUser user in userstoDelete) { //Compare the two StepUser oldUser = null; StepUser newUser = null; foreach(StepUser oldie in OldUsers) { if (user.UserId == oldie.UserId) oldUser = oldie; } foreach (StepUser newie in NewUsers) { if (user.UserId == newie.UserId) newUser = newie; } if(oldUser != null &amp;&amp; newUser != null) { if (oldUser.Role != newUser.Role) UpdatedRoles.Add(newUser.Name, newUser.Role); } OldUsers.Remove(user); NewUsers.Remove(user); } } } catch(Exception ex) { string errorMessage = String.Format("Error generating diff between Step objects {0} and {1}", NewStep.Id, SavedStep.Id); log.Error(errorMessage,ex); throw; } } </code></pre> <hr> <p>The targeted framework is 3.5.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload