title: Pivoting in Linq
body: <p>I am using LINQ-to-Entities, and would like to perform a pivot.</p>
  
  <p>For exampe, I have this table:</p>
  
  <pre><code>| data1 | data2 |
  +-------+-------+
  |   1   |   A   |
  |   1   |   B   |
  |   2   |   P   |
  |   2   |   Q   |
  |   2   |   R   |
  +---------------+
  </code></pre>
  
  <p>And I want to pivot it into the following results:</p>
  
  <pre><code>| data1 | first | second | third |
  +-------+-------+--------+-------+
  |   1   |   A   |   B    | NULL  |
  |   2   |   P   |   Q    |   R   |
  +--------------------------------+
  </code></pre>
  
  <p>I would like to do this in LINQ, without needing to do client-side processing.</p>
  
  <p>I have seen these SO posts, but they do not quite address the above situation (as far as I can tell).</p>
  
  <ul>
  <li><a href="https://stackoverflow.com/questions/963491/pivot-data-using-linq">Pivot data using LINQ</a></li>
  <li><a href="https://stackoverflow.com/questions/167304/is-it-possible-to-pivot-data-using-linq">Is it possible to Pivot data using LINQ?</a></li>
  </ul>
  
  <p><br><br>
  <strong>Note</strong>
  I have tried the below, but it complains that I cannot use Skip() on an unordered collection, and I don't see a way to get the group's collapsed 'data2' info sorted.</p>
  
  <pre><code>from item in MyTable
  group item by item.data1 into g
  select new
  {
      data1 = g.Key,
      first = g.Skip(0).FirstOrDefault().data2,
      second = g.Skip(1).FirstOrDefault().data2,
      third = g.Skip(2).FirstOrDefault().data2,
  };
  </code></pre>