Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Are you using .NET 3.5? I'm sure LINQ to Objects would make a lot of this <em>much</em> simpler.</p> <p>Another thing to think about is that if you've got a lot of code with a common pattern, where just a few things change (e.g. "which property am I comparing?" then that's a good candidate for a generic method taking a delegate to represent that difference.</p> <p>EDIT: Okay, now we know we can use LINQ:</p> <p><strong>Step 1: Reduce nesting<br /></strong> Firstly I'd take out one level of nesting. Instead of:</p> <pre><code>if (NewStep.Id != Guid.Empty &amp;&amp; SavedStep.Id != Guid.Empty) { // Body } </code></pre> <p>I'd do:</p> <pre><code>if (NewStep.Id != Guid.Empty &amp;&amp; SavedStep.Id != Guid.Empty) { return; } // Body </code></pre> <p>Early returns like that can make code much more readable.</p> <p><strong>Step 2: Finding docs to delete</strong><br/></p> <p>This would be much nicer if you could simply specify a key function to Enumerable.Intersect. You can specify an equality comparer, but building one of those is a pain, even with a utility library. Ah well.</p> <pre><code>var oldDocIds = OldDocs.Select(doc =&gt; doc.DocId); var newDocIds = NewDocs.Select(doc =&gt; doc.DocId); var deletedIds = oldDocIds.Intersect(newDocIds).ToDictionary(x =&gt; x); var deletedDocs = oldDocIds.Where(doc =&gt; deletedIds.Contains(doc.DocId)); </code></pre> <p><strong>Step 3: Removing the docs</strong><br/> Either use the existing foreach loop, or change the properties. If your properties are actually of type List&lt;T> then you could use RemoveAll.</p> <p><strong>Step 4: Updating and removing users</strong><br /></p> <pre><code>foreach (StepUser deleted in usersToDelete) { // Should use SingleOfDefault here if there should only be one // matching entry in each of NewUsers/OldUsers. The // code below matches your existing loop. StepUser oldUser = OldUsers.LastOrDefault(u =&gt; u.UserId == deleted.UserId); StepUser newUser = NewUsers.LastOrDefault(u =&gt; u.UserId == deleted.UserId); // Existing code here using oldUser and newUser } </code></pre> <p>One option to simplify things even further would be to implement an IEqualityComparer using UserId (and one for docs with DocId).</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