如何将字符串集合作为TextReader传递?

Pro*_*ofK 5 c# csv stream

我正在使用CSVHelper库,该库只需三行代码即可从CSV文件提取对象列表:

var streamReader = // Create a reader to your CSV file.
var csvReader = new CsvReader( streamReader );
List<MyCustomType> myData = csvReader.GetRecords<MyCustomType>();
Run Code Online (Sandbox Code Playgroud)

但是,按文件包含无意义的行,我需要跳过文件中的前十行。我认为使用LINQ来确保“干净”数据,然后将该数据传递给会很好CsvFReader,就像这样:

public TextReader GetTextReader(IEnumerable<string> lines)
{
    // Some magic here. Don't want to return null;
    return TextReader.Null;
}
public IEnumerable<T> ExtractObjectList<T>(string filePath) where T : class
{
    var csvLines = File.ReadLines(filePath)
                        .Skip(10)
                        .Where(l => !l.StartsWith(",,,"));
    var textReader = GetTextReader(csvLines);
    var csvReader = new CsvReader(textReader);
    csvReader.Configuration.ClassMapping<EventMap, Event>();
    return csvReader.GetRecords<T>();
}
Run Code Online (Sandbox Code Playgroud)

但是我真的很想通过像这样的流推送“静态”字符串集合TextReaer

我的替代方法是通过CsvReader逐行处理CSV文件,并在提取对象之前检查每一行,但我发现这有点笨拙。

dtb*_*dtb 6

StringReader类提供了包装字符串的TextReader。您可以简单地将这些行连接起来并将它们包装在StringReader中:

public TextReader GetTextReader(IEnumerable<string> lines)
{
    return new StringReader(string.Join("\r\n", lines));
}
Run Code Online (Sandbox Code Playgroud)

  • 最好使用 `Environment.NewLine` 作为分隔符 (2认同)