Skip to content

Instantly share code, notes, and snippets.

@nitinjs
Created September 28, 2018 08:43
Show Gist options
  • Save nitinjs/921c5947bea7389bbb9be4f110e5cbb4 to your computer and use it in GitHub Desktop.
Save nitinjs/921c5947bea7389bbb9be4f110e5cbb4 to your computer and use it in GitHub Desktop.
Generic class to parse pipe separated text into object
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication4
{
public class LineParser<T> where T : class
{
public T Parse(string line)
{
var propertyDictionary =
typeof(T)
.GetProperties(BindingFlags.Instance | BindingFlags.Public)
// create an anonymous object to hold the property and the ColumnInfo
.Select(p => new
{
Property = p,
ColumnInfo = p.GetCustomAttribute<ColumnInfoAttribute>()
})
// get only those where the ColumnInfo is not null (in case there are other properties)
.Where(ci => ci.ColumnInfo != null)
// create a dictionary with the Index as a key
.ToDictionary(ci => ci.ColumnInfo.Index);
var result = Activator.CreateInstance<T>();
var values = line.Split('|');
for (var i = 0; i < values.Length; i++)
{
// set the corresponding property
var converterdValue = Convert.ChangeType(
values[i],
propertyDictionary[i].Property.PropertyType);
propertyDictionary[i].Property.SetValue(result, converterdValue);
}
return result;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment