我希望能够过滤掉CSV文件,并对过滤后的数据执行数据验证。我设想循环,但文件有200万个单元,需要很长时间。我使用Lumenworks CSVReader来使用C#访问文件。
我找到了这个方法csvfile.Where<>,但是我不知道在参数中放什么。对不起,我对编码还不熟悉。
编辑这是我加载文件的代码。谢谢你的帮助!
//Creating C# table from CSV data
var csvTable = new DataTable();
var csvReader = new CsvReader(newStreamReader(System.IO.File.OpenRead(filePath[0])), true);
csvTable.Load(csvReader);
//grabs header from the CSV data table
string[] headers = csvReader.GetFieldHeaders(); //this method gets the headers of the CSV file
string filteredData[] = csvReader.Where // this is where I would want to implement the where method, or some sort of way to filter the data
//I can access the rows and columns with this
csvTable.Rows[0][0]
csvTable.Columns[0][0]
//After filtering (maybe even multiple filters) I want to add up all the filtered data (assuming they are integers)
var dataToValidate = 0;
foreach var data in filteredData{
dataToValidate += data;
}
if (dataToValidate == 123)
//data is validated发布于 2022-04-22 21:17:38
我将阅读您正在使用的包的一些文档:
https://github.com/phatcher/CsvReader
https://www.codeproject.com/Articles/9258/A-Fast-CSV-Reader
要具体回答筛选问题,它只包含您正在搜索的数据,请考虑以下几点:
var filteredData = new List<List<string>>();
using (CsvReader csv = new CsvReader(new StreamReader(System.IO.File.OpenRead(filePath[0])), true));
{
string searchTerm = "foo";
while (csv.ReadNextRecord())
{
var row = new List<string>();
for (int i = 0; i < csv.FieldCount; i++)
{
if (csv[i].Contains(searchTerm))
{
row.Add(csv[i]);
}
}
filteredData.Add(row);
}
}这将为您提供一个字符串列表,您可以对其进行枚举以进行验证。
int dataToValidate = 0;
foreach (var row in filteredData)
{
foreach (var data in row)
{
// do the thing
}
}--老答案
如果没有看到加载文件所用的代码,那么给出一个完整的答案可能会有点困难,无论发生什么,大约200万个单元可能会很慢。你的.Where来自System.Linq https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.where?view=net-6.0
一个使用.Where的简单示例
//Read the file and return a list of strings that match the where clause
public List<string> ReadCSV()
{
List<string> data = File.ReadLines(@"C:\Users\Public\Documents\test.csv");
.Select(line => line.Split(','))
// token[x] where x is the column number, assumes ID is column 0
.Select(tokens => new CsvFileStructure { Id = tokens[0], Value = tokens[1] })
// Where filters based on whatever you are looking for in the CSV
.Where(csvFileStructure => csvFileStructure.Id == "1")
.ToList();
return data;
}
// Map of your data structure
public class CsvFileStructure
{
public long Id { get; set; }
public string Name { get; set; }
public string Value { get; set; }
}根据这一答复修改如下:
发布于 2022-04-25 20:48:38
没有csvreader.Where方法。"where“是C#中Linq的一部分。下面的链接显示了使用Linq计算csv文件中的列的示例:
https://stackoverflow.com/questions/71974518
复制相似问题