Note that there are some explanatory texts on larger screens.

plurals
  1. POTricky LINQ query for text file format transformation
    primarykey
    data
    text
    <p>I have a shopping list in a text file, like this:</p> <pre><code>BuyerId Item; 1; Item1; 1; Item2; 1; ItemN; 2; Item1; 2; ItemN; 3; ItemN; </code></pre> <p>I need to transform this list to a format like this:</p> <pre><code>Item1; Item2; Item3; ...; ItemN &lt;--- For buyer 1 Item1; ...; ItemN &lt;--- For buyer 2 Item1; ...; ItemN &lt;--- For buyer 3 </code></pre> <p>First I parse the CSV file like this:</p> <pre><code>IList&lt;string[]&gt; parsedcsv = (from line in lines.Skip(1) let parsedLine = line.TrimEnd(';').Split(';') select parsedLine).ToList(); </code></pre> <p>Then I group the items with LINQ and aggregate them to the final format:</p> <pre><code>IEnumerable&lt;string&gt; buyers = from entry in parsedcsv group entry by entry[0] into cart select cart.SelectMany(c =&gt; c.Skip(1)) .Aggregate((item1, item2) =&gt; item1 + ";" + item2).Trim(); </code></pre> <p>HOWEVER, as it happens, the BuyerId is not unique, but repeats after a number of times (for example, it can repeat like this: 1,2,3,4,5,1,2,3,4,5,1,2,3 or like this 1,2,3,1,2,3,1,2).</p> <p>No big deal, I could quite easily fix this by grouping the items in a loop that checks that I only deal with one buyer at a time:</p> <pre><code>int lastBatchId = 0; string currentId = parsedcsv[0][0]; for (int i = 0; i &lt; parsedcsv.Count; i++) { bool last = parsedcsv.Count - 1 == i; if (parsedcsv[i][0] != currentId || last) { IEnumerable&lt;string&gt; buyers = from entry in parsedcsv.Skip(lastBatchId) .Take(i - lastBatchId + (last ? 1 : 0)) ... lastBatchId = i; currentId = parsedcsv[i][0]; ... </code></pre> <p>... however, this is not the most elegant solution. I'm almost certain this can be done only with LINQ.</p> <p>Can anyone help me out here please ?</p> <p>Thanks!</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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