title: How to Merge items within a List<> collection C#
body: <p>I have a implememtation where i need to loop through a collection of documents and based on certain condition merge the documents .</p>
  
  <p>The merge condition is very simple, if present document's doctype is same as later document's doctype, then copy all the pages from the later doctype and append it to the pages of present document's and remove the later document from the collection.
  Note : Both <code>response.documents</code> and <code>response.documents[].pages</code> are List&lt;> collections.</p>
  
  <p>I was trying this but was getting following exception Once I remove the document.</p>
  
  <blockquote>
    <p>collection was modified enumeration may not execute</p>
  </blockquote>
  
  <p>Here is the code:</p>
  
  <pre><code>int docindex = 0;
  foreach( var document in response.documents)
  {
      string presentDoctype = string.Empty;
      string laterDoctype = string.Empty;
  
      presentDoctype = response.documents[docindex].doctype;
      laterDoctype = response.documents[docindex + 1].doctype;
  
      if (laterDoctype == presentDoctype)
      {
          response.documents[docindex].pages.AddRange(response.documents[docindex + 1].pages);
          response.documents.RemoveAt(docindex + 1);
      }
      docindex = docindex + 1;
  }
  </code></pre>
  
  <p>Ex: </p>
  
  <pre><code>reponse.documents[0].doctype = "BankStatement"   //page count = 1
  reponse.documents[1].doctype = "BankStatement"   //page count = 2
  reponse.documents[2].doctype = "BankStatement"   //page count = 2
  reponse.documents[3].doctype = "BankStatement"   //page count = 1
  reponse.documents[4].doctype = "BankStatement"   //page count = 4
  </code></pre>
  
  <p>Expected result:</p>
  
  <pre><code>response.documents[0].doctype = "BankStatement"  //page count = 10
  </code></pre>
  
  <p>Please suggest.Appreciate your help.</p>