So, I'm building export/import CSV helper. I have some performance issues in the code below. it takes me to parse CSV of 25,000 rows at 7 seconds. If someone can help, it will be awesome!
public System.IO.Stream ParseContent<T>(IEnumerable<T> entities) where T : class
{
if (entities == null)
throw new ArgumentException(nameof(entities), "List accepted is empty.");
Type type = entities.First().GetType();
PropertyInfo[] properties = type.GetProperties();
string headers = GenerateTemplate(properties);
//No headers accepted - cannot export the content
if (string.IsNullOrEmpty(headers))
return null;
string contentToExport = $"{headers}{NewLineDelimiter}";
foreach (T entity in entities)
{
if (entity == null)
continue;
string template = this.ExportLine(entity, properties);
contentToExport += $"{template}{NewLineDelimiter}";
}
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(contentToExport);
System.IO.MemoryStream memoryStream = new System.IO.MemoryStream(bytes);
return memoryStream;
}
private string ExportLine<T>(T entity, PropertyInfo[] properties) where T : class
{
if (entity == null || properties == null)
return string.Empty;
string template = "";
foreach (PropertyInfo property in properties)
{
string value = null;
if (property.PropertyType.IsGenericType && property.PropertyType.GetGenericTypeDefinition() == typeof(IEnumerable<>))
{
Type underlyingType = property.PropertyType.GetGenericArguments()[0];
if (underlyingType.IsValueType || underlyingType == typeof(string))
{
System.Collections.IEnumerable list = (System.Collections.IEnumerable)property.GetValue(entity);
value = string.Join(EnumerableValueDelimiter, list.Cast<string>());
}
}
else if (property.PropertyType.IsClass && (!property.PropertyType.IsPrimitive && !property.PropertyType.IsEnum) && property.PropertyType != typeof(string))
{
//Object type. need to be serialized
object propertyValue = property.GetValue(entity);
if (propertyValue != null)
value = JsonConvert.SerializeObject(propertyValue);
else
value = "null";
}
else
{
value = property.GetValue(entity)?.ToString();
}
if (string.IsNullOrEmpty(value))
value = "";
template += $"{value}{LineValuesDelimiter}";
}
//Removing the last delimiter at the row.
if (template.Length > 0)
template = template.Remove(template.Length - 1, 1);
return template;
}