C# 比较2个CSV文件,如果第二个文件中存在,则将其删除

C# 比较2个CSV文件,如果第二个文件中存在,则将其删除,c#,csv,C#,Csv,基本上,我想从List.csv中删除一行,如果它存在于ListToDelete.csv中,并将结果输出到另一个名为newList.csv的文件中 List.csv 1,A,V 2,B,W 3,C,X 4,D,Y 5,E,z ListToDelete.csv 3. 四, NewList.csv 1,A,V 2,B,W 5,E,z 我了解如何使用streamreader和writer读取和写入文件,但我不知道如何仅存储List.csv的第一列,以将其与ListToDelete.csv的第一列进行比较

基本上,我想从List.csv中删除一行,如果它存在于ListToDelete.csv中,并将结果输出到另一个名为newList.csv的文件中

List.csv 1,A,V 2,B,W 3,C,X 4,D,Y 5,E,z

ListToDelete.csv 3. 四,

NewList.csv 1,A,V 2,B,W 5,E,z

我了解如何使用streamreader和writer读取和写入文件,但我不知道如何仅存储List.csv的第一列,以将其与ListToDelete.csv的第一列进行比较

我最初使用split方法剥离了第一列中的所有内容来进行比较,但我还需要复制其他两列,我看不出如何正确地进行比较或循环

string list = "List.txt";
        string listDelete = "ListToDelete.txt";
        string newList = "newList.txt";

        //2 methods to store all the text in a string array so we can match the arrays. Using ReadAllLines instead of screenreader so it populates array automatically
        var array1 = File.ReadAllLines(list);
        var array2 = File.ReadAllLines(listDelete);

        // Sets all the first columns from the CSV into an array
        var firstcolumn = array1.Select(x => x.Split(',')[0]).ToArray();
        //Matches whats in firstcolumn and array 2 to find duplicates and non duplicates
        var duplicates = Array.FindAll(firstcolumn, line => Array.Exists(array2, line2 => line2 == line));
        var noduplicates = Array.FindAll(firstcolumn, line => !Array.Exists(duplicates, line2 => line2 == line));

        //Writes all the non duplicates to a different file
        File.WriteAllLines(newList, noduplicates);  
所以上面的代码生成 1. 2. 五,

但是我还需要将第二列和第三列写入一个新文件

NewList.csv 1,A,V 2,B,W
5,E,z你几乎做对了。问题是因为noduplicates是从firstcolumn中选择的,而firstcolumn只是第一列{1,2,3,4,5}。应从原始列表阵列1中选择节点副本,但不包括以其中一个副本开头的行

更正一行,如下所示,即可解决问题。输出有3行,每行有3列

var noduplicates = Array.FindAll(array1, line => !Array.Exists(duplicates, line2 => line.StartsWith(line2)));
此外,不需要解析原始数组中的第一列进行匹配。代码可以这样清理

string list = "List.csv";
string listDelete = "ListToDelete.csv";
string newList = "newList.txt";

var array1 = File.ReadAllLines(list);
var array2 = File.ReadAllLines(listDelete);

var noduplicates = Array.FindAll(array1, line => !Array.Exists(array2, line2 => line.StartsWith(line2)));

//Writes all the non duplicates to a different file
File.WriteAllLines(newList, noduplicates);

我答案中的代码对你有用吗?请替换这一行。您好,Kenny,您提供的代码可以工作,但它仍然不会在新的输出文件中生成第二列和第三列。问题是因为noduplicates是从firstcolumn中选择的,即{1,2,3,4,5}。我相信我已经解决了这个问题:我从原始列表中选择了1,不包括以3/4开头的两行。当然,我很抱歉,我错过了。非常感谢。