title: How to merge multiple lines in a csv file based on search criteria in C#?
body: <p>Is there a simple way of searching through an array of csv strings and then writing certain bits of the data in one line. Currently It searches through a csv file and pulls out certain data based on two user inputs from TextBoxes, then sorts this and writes it into another csv file.</p>
  
  <p>Essentially, I would like it to write data on the same line if the device name is the same. Lets say a device is called "dev1 id1" and another device is called "dev1 id2". Instead of writing both on separate lines (like it currently does), I would like it to write in on a single combined line. Something like:</p>
  
  <pre><code>dev1,id1,id2
  </code></pre>
  
  <p>Instead of:</p>
  
  <pre><code>dev1,id1
  
  dev1,id2
  </code></pre>
  
  <p>I have tried using for loops and if statements but it gets messy quickly. Bellow is my current code (sorry for any typo's due to work reasons i had to retype it).</p>
  
  <pre><code>StreamWriter sw = new StreamWriter(@"c:\test.csv");
  StreamReader sr = new StreamReader(@"c:\rtest.csv");
  
  List&lt;string&gt; list = new List&lt;string&gt;();
  string line = "Station,Device,Key,AOR";
  string sta = textBox1.Text;
  string[] devs = richTextBox1.Text.Split(',').Select(dev =&gt; dev.Trim()).ToArray();
  string[] sort,strs;
  bool cont;
  
  sw.WriteLine(line);
  
  while (!sr.EndOfStream)
  {
      strs = line.Split(',');
      cont = (devs.Any(s =&gt; strs[1].IndexOf(s, StringComparison.OrdinalIgnoreCase) &gt;= 0));
      if (strs[2].ToString() == sta &amp;&amp; cont ==true)
      {
          list.Add(line.ToString());
      }
      line = sr.ReadLine();
  }
  sort = new string[list.Count];
  list.CopyTo(sort);
  Array.Sort(sort);
  
  foreach (string var in sort)
  {
      strs = var.Split(',');
      sw.WriteLine(string.Format("{2},{1},{0},{3}", strs[0], strs[1], strs[2], strs[3]));
  }
  
  sw.Close();
  if (File.Exists(@"c:\test.csv")
  {
      Process.Start(@"c:\test.csv");
  }
  </code></pre>
  
  <p>Hope my question is understandable, thanks.</p>