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

时间:2019-04-07 20:15:58

标签: c# 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]

依此类推。

1 个答案:

答案 0 :(得分:1)

  

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

因此,我们将其分为三个单独的部分:

  • 提供文件名,打开文件并读取一系列行
  • 给定一系列行,将其更改为[index,line]序列
  • 根据[index,line]的序列将其更改为所需的字符串格式

当然,我们想做的都非常像LINQ,因为我们喜欢LINQ(双关语意)

让我们编写扩展功能。参见Extension Methods Demystified

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();
        }
    }

将一系列行转换为一系列[索引,行]

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);

简单的漫画卓悦!

相关问题