繁体   English   中英

如何使用 LINQ 将 .csv 文件读入数组

[英]How to read .csv file into array using LINQ

我有一个逗号分隔值文件 (csv),我想打开 csv 文件并使用 C# 中的 LINQ 将每一行读入数组的索引。 我想强调的是,我特别需要在数组中使用它。

Subject,CourseCode,Class Nbr,Course Title,Days
LST,101,17297,The LST Experience,Th
RTO,101,13998,The RTO Experience,T

我希望数组的第一个索引能够打印以下内容

LST,101,17297,The LST Experience,Th //array[0]

等等等等。

我想打开 csv 文件并在 C# 中使用 LINQ 将每一行读入数组的索引。

所以让我们把它分成三个独立的部分:

  • 给定文件名,打开文件并读取一系列行
  • 给定一系列行,将其更改为 [index, line] 的序列
  • 给定一系列 [index, line] 将其更改为您想要的字符串格式

当然,我们希望这一切都非常类似于 LINQ,因为我们喜欢 LINQ(双关语)

让我们来编写扩展函数。 请参阅揭开扩展方法的神秘面纱

static class MyExtensionMethods
{
    // TODO add the extension methods
}

第一种:输入一个字符串fileName,输出一串行(=字符串)

public static IEnumerable<string> ReadLines(this string fileName)
{
    // TODO: check fileName not null, empty; check file exists
    FileInfo file = new FileInfo(fileName);
    using (TextReader reader = file.OpenText())
    {
        string line = reader.ReadLine();
        while (line != null)
        {
            yield return line;
            line = reader.ReadLine();
        }
    }

将 Lines 序列转换为 [index, line] 序列

IEnumerable<KeyValuePair<int, string>> ToIndexedLines(this IEnumerable<string> lines)
{
    return lines.Select( (line, index) => new KeyValuePair<int, string>(index, line));
}

第三个函数:给定一个 [index, line] 的序列,将其转换为一个字符串序列。

为了使其可重用,我将使用格式字符串,以便调用者可以决定如何打印他的输出。 格式字符串具有索引{0}{1}

IEnumerable<string> ToString(this IEnumerable<KeyValuePair<int, string>> indexLines,
   string formatString)
{
    // TODO: check input not null
    return indexLines.Select(keyValuePair =>
           String.Format(formatString, keyValuePair.Key, keyValuePair.Value);
}

在三个单行函数之后,我们能够以类似 LINQ 的方式读取您的文件

const string fileName = "MyFile.Csv";
const string myFormatString = "{1} //array[{0}]";

IEnumerable<string> myRequestedOutput = fileName.ReadLines()
    .ToIndexedLines()
    .ToString(myFormatString);

简单的来吧!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM