Michael Tucker Michael Tucker - 1 year ago 56
C# Question

Reading CSV file, match column 3 to column 1 on separate lines

I am beating my head against the wall, and I'm hoping that someone can point me in the right direction. This can't be as complicated as I'm making it.

I'm working on a project where the program reads one file (that's approx 50 lines or so) and I need to have it match data on the third column to data on the first column of a separate line. I opened up a new project because it was getting too complex for such an easy task.

Here's an example file that is closely relevant to the actual file I'm working with:


I promise this isn't for a school project, this is something that I need to figure out for work purposes.

Here is what I have, and I know it's just not going to work because it's only reading line by line for comparison. How do I get the program to read the current array value in the foreach command against the entire file that I caught in streamreader?

static void Main(string[] args)
StreamReader sr = new StreamReader("directories.txt");
string sline = sr.ReadLine();
string[] sarray = sline.Split(',');
string col3 = sarray[2];
string col1 = sarray[0];
foreach(string a in sarray)
// ?!?!?!!!
// I know this won't work because I'm comparing the same line being read.
// How in the world can I make this program read col3 of the current line being read against the entire file that was read earlier?
if (col3 == col1)
Directory.CreateDirectory("DRIVE:\\Location\\" + a.ToString());


Thank you ahead of time!

Answer Source

Since your file is small you can go with the simplest path...

var lines = File.ReadLines(filename)
            .Select(line => line.Split(','))

var result = from a in lines
             from b in lines
             where a[0] == b[2]
             select new { a, b };

foreach(var x in result)
    Console.WriteLine(string.Join(",", x.a) + " - " + string.Join(",", x.b));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download