如何在 c# 中使用列名而不是列号仅检索 csv 的几列数据

How to retrieve only few columns data of a csv using the column names instead of column number in c#

我有一个包含许多列的 csv。从那个 csv 中,我只需要 select 几个必需的列。

我写的代码是

                for (int i = 0; i < lineCount; i++)
                {
                    var line = str.ReadLine();
                    if (line != null)
                    {
                        var values = line.Split(',');
                        dataInformation.Add(new DataInformation
                        {
                            timestamp_iso = values[3],
                            last_attributed_touch_data_tilde_campaign = values[9],
                            last_attributed_touch_data_tilde_channel = values[11],
                            last_attributed_touch_data_tilde_feature = values[12],
                            last_attributed_touch_data_tilde_ad_set_name = values[19],
                            user_data_platform = values[69],
                            user_data_aaid = values[70],
                            user_data_idfa = values[71],
                            user_data_idfv = values[72]
                        });
                    }
                } 

我在使用它时得到了错误的值。是否有任何其他方法可以使用列名而不是列号来检索值。

数据信息是class

public class DataInformation
    {
        public string timestamp_iso { get; set; }
        public string last_attributed_touch_data_tilde_campaign { get; set; }
        public string last_attributed_touch_data_tilde_channel { get; set; }
        public string last_attributed_touch_data_tilde_feature { get; set; }
        public string last_attributed_touch_data_tilde_ad_set_name { get; set; }
        public string user_data_platform { get; set; }
        public string user_data_aaid { get; set; }
        public string user_data_idfa { get; set; }
        public string user_data_idfv { get; set; }
    }

请帮我解决这个问题。

我推荐使用库来处理 CSV 格式。 CsvHelper 不错。它允许按列名访问字段:

csv.Read();
var field = csv["HeaderName"];

CSV 格式可能看起来很简单,但存在一些极端情况(如引号),因此最好使用现有的解决方案。

我已经使用下面的代码获取了 DataInformation 类型的所有记录。

            using (TextReader fileReader = File.OpenText(FileName))
            {
                var csv = new CsvReader(fileReader);
                dataInformation = csv.GetRecords<DataInformation>().ToList();
            }

然后我使用下面的代码来获取所需的列。

            using (TextWriter writer = new StreamWriter(ConfigurationManager.AppSettings["downloadFilePath"] + ConfigurationManager.AppSettings["fileName"] + date + ConfigurationManager.AppSettings["csvExtension"].ToString()))
            {
                using (var csv = new CsvWriter(TextWriter.Synchronized(writer)))
                {
                    csv.WriteHeader(typeof(DataInformation));
                    csv.NextRecord();
                    csv.WriteRecords(dataInformation);
                }
            }

对我有用。