【发布时间】: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开头的两行。 -
当然,我很抱歉,我错过了。谢谢