Skip to content

Instantly share code, notes, and snippets.

@offpepe
Created June 2, 2023 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save offpepe/c54c919f6996e30a4a285c5c33ab9865 to your computer and use it in GitHub Desktop.
Save offpepe/c54c919f6996e30a4a285c5c33ab9865 to your computer and use it in GitHub Desktop.
class -> csv [c#]
public static string ConvertToCommaSeparatedValues<T>(this IEnumerable<T> objects) where T : class
{
var builder = new StringBuilder();
var properties = typeof(T).GetProperties();
builder.Append(string.Join(",", properties.Select(p => p.Name)));
builder.Append('\n');
foreach (var obj in objects)
{
var objValues = obj.GetType().GetProperties()
.Select(op => op.GetValue(obj));
builder.Append(string.Join(",", objValues));
builder.Append('\n');
}
return builder.ToString();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment