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.
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:
dev1,id1,id2
Instead of:
dev1,id1
dev1,id2
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).
StreamWriter sw = new StreamWriter(@"c:\test.csv");
StreamReader sr = new StreamReader(@"c:\rtest.csv");
List<string> list = new List<string>();
string line = "Station,Device,Key,AOR";
string sta = textBox1.Text;
string[] devs = richTextBox1.Text.Split(',').Select(dev => dev.Trim()).ToArray();
string[] sort,strs;
bool cont;
sw.WriteLine(line);
while (!sr.EndOfStream)
{
strs = line.Split(',');
cont = (devs.Any(s => strs[1].IndexOf(s, StringComparison.OrdinalIgnoreCase) >= 0));
if (strs[2].ToString() == sta && 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");
}
Hope my question is understandable, thanks.