解析CSV字符串或文件是一个相当简单的任务。循环遍历所有行并在分隔符字符处使用String.Split
进行拆分。无论您是否使用库来为您完成此操作,这取决于您。
这是我想出的一个非常灵活的TextReader扩展方法:
using System;
using System.Collections.Generic;
using System.IO;
namespace Extensions
{
public static class TextReaderExtensions
{
public static IEnumerable<T> ParseCsvData<T>(this TextReader reader, Func<string[], T> mapFunction, char separator = ',', short skipLines = 1)
{
IEnumerable<string[]> readCsvLines()
{
string line;
while ((line = reader.ReadLine()) != null)
{
if (!string.IsNullOrEmpty(line) && skipLines-- < 1)
{
yield return line.Split(separator);
}
}
}
foreach (var csvLine in readCsvLines())
{
yield return mapFunction.Invoke(csvLine) ?? default;
}
}
}
}
从字符串输入的示例用法:
using (var textReader = new StringReader("Comma,Separated,Value,String"))
{
var persons = textReader.ParseCsvData(columns => new Person
{
Id = columns[0],
Name = columns[1],
Age = columns[2]
});
return persons.ToList();
}
从文件流输入的示例用法:
using (var textReader = new StreamReader(fileStream))
{
var formattedStrings = textReader.ParseCsvData(data => data[1] + " is " + data[2] + " years old.");
return formattedStrings.ToList();
}
无限的可能性。
做任何你想做的事情...
人民有力量!!