[英]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 將每一行讀入數組的索引。
所以讓我們把它分成三個獨立的部分:
當然,我們希望這一切都非常類似於 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.