如何删除csv文件中的行 [英] How to delete the rows in csv file
问题描述
我有两个csv文件.Example1.csv和Example2.csv。
示例1有三列,其中包含1.S.No.2.Phoone编号3.移动编号
示例2有许多列,其中列有列在示例1 csv文件中有。
示例1.csv文件
S.no Ph num Mobile Num
1 123 234
2 254 125
例2.csv
Column1 column2 Column3 column4 column5
1 45 456 123 234
2 89 898 254 124
3 85 365 789 454
现在我需要删除example2.csv中的行(第1和第2行应删除,因为它们的电话号码和移动号码都匹配)与示例1文件中的数据匹配。
Hi ,
I have two csv files .Example1.csv and Example2.csv.
Example 1 has three columns which has 1.S.No.2.Phoone number 3.Mobile number
Example 2 has many columns in which it has the columns that are there in example 1 csv file.
Example1.csv file
S.no Ph num Mobile Num
1 123 234
2 254 125
Example 2.csv
Column1 column2 Column3 column4 column5
1 45 456 123 234
2 89 898 254 124
3 85 365 789 454
Now i need to delete the rows in example2.csv (Roww 1 and 2 should be removed as they both the phone num and mobile num matches )that matches with data in example 1 file.
IList<string> Example1 = File.ReadAllLines(Example1 )
foreach (var item in wdlCsvFile1)
{
var list = item.Split(',');
column1.Add(list[0]);
column2.Add(list[1]);
column3.Add(list[2]);
//column4.Add(list[3]);
}
IList<string> Example2= File.ReadAllLines(Example2);
Example2.ToList();
foreach (var item in Example2)
{
var itemIndex = filedetails.IndexOf(item);
var list = item.Split(";");
string phone= list.GetValue(4).ToString();
string mobile= list.GetValue(5).ToString();
if (column2.Contains(phone) &&column3.Contains(mobile))
{
example2.delete(item);
}
}
但是当我尝试删除它时,我收到一个错误,如固定大小的数组收集。
请帮帮我。我用Google搜索了很多方法,但我找不到ans。
but when i try to remove it i aam receiving an error like "fixed size array collection" .
Please help me out .i ahve googled in so many ways but i couldnt find the ans.
推荐答案
如果修复了某些集合,请不要尝试删除该行。从文件填充数据时跳过不需要的行。您可以逐行阅读,而不是使用ReadAllLines
,而在每个类似的情况下,您可以决定是否要跳过它。对于您填充的集合,请使用System.Collections.Generic.List< string>
。而不是文件
,使用类System.IO.StreamReader
:
http://msdn.microsoft.com/en-us/library/system.io.streamreader.aspx [ ^ ]。
它可能是这样的:
If some collection is fixed, don't try to delete the row. Skip unwanted row when you populate the data from file. Instead of usingReadAllLines
, you could read line by line and, on each like, decide if you want to skip it. For the collection you populate, useSystem.Collections.Generic.List<string>
. Instead ofFile
, use the classSystem.IO.StreamReader
:
http://msdn.microsoft.com/en-us/library/system.io.streamreader.aspx[^].
It could be something like:
System.Collections.Generic.List<string> list = new System.Collections.Generic.List<string>();
using (System.IO.StreamReader reader = new System.IO.StreamReader(fileName) {
string line = reader.ReadLine();
if (line /* if something's wrong with this line... */)
continue;
list.Add(line);
// ... whatever else you want to do
} // reader.Dispose is automatically called on exit from this block
顺便说一下,这种类型的列表将允许你删除项目(行),但要小心。 br $>
这篇关于如何删除csv文件中的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!