【问题标题】:c# Compare 2 CSV files and delete if it exists in second filec#比较2个CSV文件,如果它存在于第二个文件中则删除
【发布时间】:2014-10-12 12:40:50
【问题描述】:

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

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

ListToDelete.csv
3
4

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

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

我最初使用 split 方法删除了第一列中的所有内容进行比较,但我还需要复制其他 2 列,我看不到如何正确比较或循环遍历它。

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
5

但我还需要将第二列和第三列写入新文件以使其看起来像

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

【问题讨论】:

  • 我的答案中的代码对您有用吗?只需替换这一行。
  • 嗨,Kenny,您提供的代码有效,但仍然无法在新输出文件中生成第二列和第三列
  • 问题是因为noduplicates是从firstcolumn中选择的,也就是{1,2,3,4,5}。我相信我已经解决了这个问题:我从原始列表 (array1) 中选择,不包括以 3/4 开头的两行。
  • 当然,我很抱歉,我错过了。谢谢

标签: c# csv


【解决方案1】:

你几乎做对了。问题是因为noduplicates是从firstcolumn中选择的,这只是{1,2,3,4,5}的第一列。 noduplicates 应从原始列表 (array1) 中选择,不包括以其中一个重复项开头的行。

如下更正一行应该可以解决问题。输出有 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);

【讨论】:

    猜你喜欢
    • 2021-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-19
    • 1970-01-01
    相关资源
    最近更新 更多