首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >从csv文件中使用TextFieldParser和c#获取特定列的行值。

从csv文件中使用TextFieldParser和c#获取特定列的行值。
EN

Stack Overflow用户
提问于 2022-03-02 09:11:20
回答 1查看 353关注 0票数 0

我试图使用TextFieldParser和c#来解析csv文件并获取特定列的行值。

例如,csv具有..。

代码语言:javascript
运行
复制
Name,Age,Color,Sport
Tom,24,Blue,Football
Dick,21,Red,Hockey
Jane,19,Green,Basketball

string fullpath = "C:\myfile.csv"
using (TextFieldParser parser = new TextFieldParser(fullPath))
{
     parser.SetDelimiters(",");
     while (!parser.EndOfData)
     {
        // Processing row
        string[] fields = parser.ReadFields();
        int sportcount = 0;
        for (int i = 0; i < fields.Length; ++i)
        {
            string column = fields[i];
            DataColumn datecolumn = new DataColumn(column);
            datecolumn.AllowDBNull = true;
            if (column.Contains("Sport"))
            {
                Console.WriteLine("Found Sport at {0}", i);
                sportcount = i;
            }
        }
        string sportCol = fields[sportCount];

        // if that column contains a value
        if (!(sportCol.Equals("")) {
            // ignore the column header row
            if (parser.LineNumber > 2) {
                if (sportCol.Equals("Football")) {
                    Console.WriteLine("Found somebody playing football");
                }
            }
        }
    }
}

因此,我想要一个列表或数组,其中包含csv文件中的所有项目。所以它应该包含(足球,曲棍球,篮球)。请记住,实际的csv文件有数百列和数千行。

更新:我已经将上面的内容更新为对我有用的东西。通过在变量找到“体育”列时将我分配给它,然后我可以通过csv文件向下搜索该列的值。

EN

回答 1

Stack Overflow用户

发布于 2022-03-02 09:19:22

我想“试一试”,你的意思是,这是你遇到的东西,可以读到csv,而你并没有执着于它。因此,我想指出,如果您使用CsvHelper来读取这个文件,情况会如何:

代码语言:javascript
运行
复制
public class Person
{
    public int Age { get; set; }
    public string Name { get; set; }
    public string Color { get; set; }
    public string Sport { get; set; }
}

//in a method somewhere
using var reader = new StreamReader("path\\to\\file.csv"));
using var csv = new CsvReader(reader, CultureInfo.InvariantCulture));

foreach(var person in  csv.GetRecords<Person>()){
    //put code here
    Console.WriteLine(person.Name);

}

实际的csv文件有数百列

您需要为每一列创建一个属性

理想上,我想要一个列表或数组,其中包含csv文件中的所有项目

每项运动都有明确的清单?

相反,请做:

代码语言:javascript
运行
复制
csv.GetRecords<Person>().Select(p => p.Sport).Distinct().ToArray()

请记住,以这种方式读取CSV是向前的,因此您不能第二次调用getRecords而不将读取器重置到文件的开始。也许,如果你有更多的事情要做,你应该:

代码语言:javascript
运行
复制
var people = csv.GetRecords<Person>().ToList();

若要将其全部加载到内存中,则可以重复查询:

代码语言:javascript
运行
复制
people.Sum(p => p.Age); //sum of all ages
people.Avg(p => p.Age); //avg age
people.Count(p => p.Color == "Red"); //count of reds
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71320083

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档