Skip to content

Instantly share code, notes, and snippets.

@ahmetkucukoglu
Created November 8, 2023 19:58
Show Gist options
  • Save ahmetkucukoglu/86a9e2e8fc54f675efc73d0567341d09 to your computer and use it in GitHub Desktop.
Save ahmetkucukoglu/86a9e2e8fc54f675efc73d0567341d09 to your computer and use it in GitHub Desktop.
Adaptee - CsvHelper
public class CsvHelper
{
private char Delimiter { get; set; }
public CsvHelper(char delimiter)
{
Delimiter = delimiter;
}
public string GenerateCsv(List<object> rows)
{
if (rows == null) return string.Empty;
var objectType = rows.FirstOrDefault()!.GetType();
var headers = objectType.GetProperties().Select(x => x.Name).ToList();
var stringBuilder = new StringBuilder();
stringBuilder.AppendLine(string.Join(Delimiter, headers));
foreach (var row in rows)
{
var values = objectType.GetProperties().Select(prop => prop.GetValue(row)).ToList();
stringBuilder.AppendLine(string.Join(Delimiter, values));
}
return stringBuilder.ToString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment