A generic class to get object collection from csv string. I would like to know if there's any better way?
Converter class
public class CsvConverter<T>:List<T> where T:class
{
private readonly string _csvText;
private readonly string _separetor;
/// <summary>
/// Get object collection from CSV string
/// </summary>
/// <param name="csvText">CSV string with Title</param>
/// <param name="separator">CSV line separator</param>
public CsvConverter(string csvText, string separator= "\r\n")
{
this._csvText = csvText;
_separetor = separator;
BuildObject();
}
/// <summary>
/// Get CSV string from collection of objects
/// </summary>
/// <param name="collection">Pass collection of objects</param>
public CsvConverter(IEnumerable<T> collection)
{
foreach (var item in collection)
{
this.Add(item);
}
}
/// <summary>
/// Create new Instance of T object
/// </summary>
/// <returns></returns>
protected T GetObject()
{
return (T)Activator.CreateInstance(typeof(T),true);
}
/// <summary>
/// Build object from CSV string to collection
/// </summary>
private void BuildObject()
{
if (!string.IsNullOrEmpty(_csvText))
{
//Get first line from CSV string, than split by comma to get column names
var _csvLines = _csvText.Split(_separetor);
var _columnName =_csvLines[0].Split(',');
for (int i = 1; i < _csvLines.Length; i++)
{
var line = _csvLines[i].Split(',');
T obj = GetObject();
Type t = obj.GetType();
PropertyInfo[] props = t.GetProperties();
int colIndx = 0;
foreach (string str in line)
{
PropertyInfo find = props.First(x => x.Name == _columnName[colIndx]);
find.SetValue(obj, Convert.ChangeType(str,find.PropertyType),null);
//propertyInfo.SetValue(propertyInfo.PropertyType, line[0]);
colIndx++;
}
this.Add(obj);
}
}
else
{
throw new System.NullReferenceException("No CSV string has passed in the parameter");
}
}
/// <summary>
/// Returns CSV string from collection of T object
/// </summary>
/// <returns>string</returns>
public string GetCsvString()
{
StringBuilder sb = new StringBuilder();
foreach (var item in this)
{
Type t = item.GetType();
PropertyInfo[] props = t.GetProperties();
string ln = "";
foreach (PropertyInfo prp in props)
{
ln= ln+($"{prp.GetValue(item)},");
}
sb.AppendLine($"{ln.TrimEnd(',')}");
}
return sb.ToString();
}
}
get collection of object from csv string
var csv = await System.IO.File.ReadAllTextAsync("test.csv");
List<TestC> csvBarcode = new CsvConverter<TestC>(csv.TrimEnd());
get csv string from collection of object
CsvConverter<TestC> b = new CsvConverter<TestC>(list);
return Content(b.GetCsvString());
List<T>? \$\endgroup\$