首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何使用LINQ将.csv文件读入数组

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

Stack Overflow用户
提问于 2019-04-08 04:15:58
回答 1查看 510关注 0票数 2

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

代码语言:javascript
运行
复制
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]

以此类推。

EN

回答 1

Stack Overflow用户

发布于 2019-04-10 22:36:19

我想要打开csv文件,并在C#中使用

将每一行读入数组的索引。

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

  • 给定文件名,打开文件并读取一系列行
  • 给定一系列行,将其更改为索引序列,line
  • 给定索引序列,line将其更改为所需的字符串格式

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

让我们来编写扩展函数。请参阅Extension Methods Demystified

代码语言:javascript
运行
复制
static class MyExtensionMethods
{
    // TODO add the extension methods
}

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

代码语言:javascript
运行
复制
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();
        }
    }

将行序列转换为索引、行序列

代码语言:javascript
运行
复制
IEnumerable<KeyValuePair<int, string>> ToIndexedLines(this IEnumerable<string> lines)
{
    return lines.Select( (line, index) => new KeyValuePair<int, string>(index, line));
}

第三个函数:给定一个索引序列,将其转换为字符串序列。

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

代码语言:javascript
运行
复制
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的方式读取您的文件

代码语言:javascript
运行
复制
const string fileName = "MyFile.Csv";
const string myFormatString = "{1} //array[{0}]";

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

简单的comme bonjour!

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55563273

复制
相关文章

相似问题

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