从多个 CSV 文件中仅读取特定列

Use*_*987 4 c# csv asp.net asp.net-mvc file

我有一个 CSV 文件,基本上如下所示:

TransactionID         ProfileID       Date           // more columns here...
somevalue             123123123      somedate
somevalue             123123123      somedate              
somevalue             123123123      somedate
somevalue             123123123      somedate
somevalue             123123123      somedate
Run Code Online (Sandbox Code Playgroud)

我只想从 CSV 文件中的所有这些列中提取 ProfileID 和 Date 的特定列,方法是将其映射到这样的现有类:

public class MyMappedCSVFile
{
  public string ProfileID { get; set; } 
  public string Date { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

还是将其存储在 Dictionary 集合中?

我试过这样的事情:

   public static List<string> ReadInCSV(string absolutePath)
        {
            List<string> result = new List<string>();
            string value;
            using (TextReader fileReader = File.OpenText(absolutePath))
            {
                var csv = new CsvReader(fileReader);
                csv.Configuration.HasHeaderRecord = false;
                while (csv.Read())
                {
                    for (int i = 0; csv.TryGetField<string>(i, out value); i++)
                    {
                        result.Add(value);
                    }
                }
            }
            return result;
        }
Run Code Online (Sandbox Code Playgroud)

但这会从 CSV 文件中取出所有内容,实际上是单个列表中的所有内容,这不是我想要的......

有人可以帮我解决这个问题吗?

kur*_*rdy 6

此代码中的标题仍要跳过,但使用此代码,您可以选择要提取的列。如果您使用 StreamReader,它可能会快得多。您将需要一个对象的构造函数。

var temp = File.ReadAllLines(@"C:\myFile.csv");
public List<MyMappedCSVFile>() myExtraction = new List<MyMappedCSVFile>();
foreach(string line in temp)
{
  var delimitedLine = line.Split('\t'); //set ur separator, in this case tab

  myExtraction.Add(new MyMappedCSVFile(delimitedLine[0], delimitedLine[3]));
}
Run Code Online (Sandbox Code Playgroud)

您的对象的代码:

public class MyMappedCSVFile
{
  public string ProfileID { get; set; } 
  public string Date { get; set; }

  public MyMappedCSVFile(string profile, string date)
  {
    ProfileID = profile;
    Date = date;
  }
}
Run Code Online (Sandbox Code Playgroud)