读取CSV文件,在单独的行上匹配列3和列1

本文关键字:和列 文件 CSV 单独 读取 | 更新日期: 2023-09-27 18:11:31

我头都撞墙了,我希望有人能给我指出正确的方向。这不能像我写的那么复杂。

我正在研究一个项目,其中程序读取一个文件(大约50行左右),我需要将第三列上的数据与单独一行的第一列上的数据匹配。我开始了一个新项目,因为对于这样一个简单的任务来说,它变得太复杂了。

下面是一个与我正在使用的实际文件密切相关的示例文件: a1,b1,c1,d1 **c4**,b2,c2,d2 a3,b3,c3,d3 a4,b4,**c4**,d4 a5,b5,c4,d5 我保证这不是为了学校的项目,这是我为了工作需要弄清楚的事情。

这是我的,我知道这是行不通的,因为它只是逐行读取比较。我如何让程序在foreach命令中读取我在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());
            }
        }
    }

提前感谢!

读取CSV文件,在单独的行上匹配列3和列1

由于您的文件很小,您可以使用最简单的路径…

var lines = File.ReadLines(filename)
            .Select(line => line.Split(','))
            .ToList();
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));
}