Sprache: C#
Konvertiert eine CSV-Datei mit n-Spalten.
Der Funktion wird der Separator, der Dateiname, die Filterfunktion (Filter über Zeilennummer möglich) und das Zielformat als Lambda-Expression übergeben.
Dabei ruft der Converter Zeilenweise die Projection auf um die konvertierung durchzuführen.
Beispiel:
[code]XElement result = new XElement( "root",
ConvertCsvTo<XElement> ( "felder_mit_beschreibung.txt", 't',
row => row > 0,
columns => new XElement ( "bereich",
new XAttribute ( "name", columns[ 0 ] ),
new XElement ( "feld",
new XElement ( "name", columns[ 2 ] ),
new XElement ( "beschreibung", columns[ 1 ] )))));[/code]
In diesem Beispiel wird die Ergebnissmenge in einen Wurzelknoten (root) gepackt. Transformiert wird eine CSV-Datei mit 3 Spalten, die durch einen Tabulator getrennt ist. Der Header interessiert dabei nicht, daher die Filterbedingung row > 0. Zum Schluss werden die Spalten in einem gewüschten Format in Form gebracht. Hier XML.
Genauso denkbar wäre eine Projektion auf XAML, Excell-Tabelle,vielleicht HTML, oder was auch immer.
/// <summary>
/// Converts a CSV-File to any desired Format. The File is read line by line
/// and splitted with the separator
/// </summary>
/// <typeparam name="TTarget">The type of the target.</typeparam>
/// <param name="filename">The filename.</param>
/// <param name="separator">The separator.</param>
/// <param name="predicate">The predicate determining wether a can row should be parsed</param>
/// <param name="projection">The projection.</param>
/// <returns></returns>
public static IEnumerable<TTarget> ConvertCsvTo<TTarget> (
string filename,
char separator,
Predicate<int> predicate,
Func<string[], TTarget> projection )
{
int rowCount = 0;
return from row in File.ReadAllLines ( filename )
where predicate ( rowCount++ )
let columns = row.Split ( separator )
select projection ( columns );
}
/// <summary>
/// Converts a CSV-File to any desired Format. The File is read line by line
/// and splitted with the separator
/// </summary>
/// <typeparam name="TTarget">The type of the target.</typeparam>
/// <param name="filename">The filename.</param>
/// <param name="separator">The separator.</param>
/// <param name="predicate">The predicate determining wether a can row should be parsed</param>
/// <param name="projection">The projection.</param>
/// <returns></returns>
public static IEnumerable<TTarget> ConvertCsvTo<TTarget> (
string filename,
char separator,
Predicate<int> predicate,
Func<string[], TTarget> projection )
{
int rowCount = 0;
return from row in File.ReadAllLines ( filename )
where predicate ( rowCount++ )
let columns = row.Split ( separator )
select projection ( columns );
}
Alte URL:
/snippet/generischer-converter-fuer-csv-dateien/1022