我有一个逗号分隔值文件( 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]
以此类推。
发布于 2019-04-10 22:36:19
我想要打开csv文件,并在C#中使用
将每一行读入数组的索引。
所以让我们把它分成三个独立的部分:
当然,我们想做这一切都非常像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));
}第三个函数:给定一个索引序列,将其转换为字符串序列。
为了使其可重用,我将使用格式化字符串,这样调用者就可以决定如何打印他的输出。格式字符串具有索引{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);简单的comme bonjour!
https://stackoverflow.com/questions/55563273
复制相似问题