title: How can I change from LINQ to using a simple foreach when comparing two collections?
body: <p>I have the following code which I find very confusing. What the code does is it compares the data from two collections and then issues an update, add or delete based on what has changed between oldObj and newObj.</p>
  
  <p>Is there a way that I could simplify this so that it was all just contained in three foreach loops and so I did not have to use the fancy LINQ code. If someone could give me a suggestion on how I could do the first change with just additions then even that would be a great help.</p>
  
  <pre><code>var oldObj = db.SubTopics
    .Where(t =&gt; t.TopicId == id)
    .AsNoTracking()
    .ToList();
  var newObj = topic.SubTopics.ToList();
  
  var upd = newObj
    .Where(wb =&gt; oldObj
      .Any(db1 =&gt; (db1.SubTopicId == wb.SubTopicId) &amp;&amp;
        (db1.Number != wb.Number || !db1.Name.Equals(wb.Name)
        || !db1.Notes.Equals(wb.Notes))))
      .ToList();
  
  var add = newObj
    .Where(wb =&gt; oldObj
      .All(db1 =&gt; db1.SubTopicId != wb.SubTopicId))
    .ToList();
  
  var del = oldObj
    .Where(db1 =&gt; newObj
      .All(wb =&gt; wb.SubTopicId != db1.SubTopicId))
    .ToList();
  
  foreach (var subTopic in upd)
  {
    db.SubTopics.Attach(subTopic);
    db.Entry(subTopic).State = EntityState.Modified;
  }
  foreach (var subTopic in add)
  {
    db.SubTopics.Add(subTopic);
  }
  foreach (var subTopic in del)
  {
    db.SubTopics.Attach(subTopic);
    db.SubTopics.Remove(subTopic);
  }
  </code></pre>