title: C# - Merge list items into one item based on some matching values
body: <p>I have a list of items (<code>List&lt;Tasks&gt; tasks</code>), like this one:</p>
  
  <pre class="lang-none prettyprint-override"><code>Id                     Action               Source       Target
  -------               ---------            --------     ---------
  1                      Save                 12           18
  4                      Save                 18           21
  7                      Save                 21           23
  6                      Save                 23           25
  10                     Save                 25           27
  16                     Save                 29           31
  0                      Edit                 31           37
  </code></pre>
  
  <p>What I want to do, is to merge the rows that have the same (<code>Source</code> and <code>Target</code>) and the same <code>Action</code>. For example, what I need at the end should look like this:</p>
  
  <pre class="lang-none prettyprint-override"><code>Id                     Action               Source       Target
  -------               ---------            --------     ---------
  22                     Save                 12           27
  16                     Save                 29           31
  0                      Edit                 31           37
  </code></pre>
  
  <p>Which means, all the items that have the same <code>Action</code>(in my case here Save) should be merged to one row/item <strong>but only</strong> in case the <code>Target</code> value of the upper item is equal to the <code>Source</code> value of the follower item. A follower is the lower item. </p>
  
  <p>For example, upper is item <code>Id = 1</code> and lower/follower is item <code>Id = 4</code>. So the record that follows.</p>
  
  <p>Is there any way to do this with linq avoiding the too many foreach loops?
  Maybe something like Hierarchies with CTE in SQL. But I'm still not finding the correct syntax, so that's why I didn't paste any code.</p>
  
  <p>Thanks in advance!</p>