Created
September 28, 2018 08:43
-
-
Save nitinjs/921c5947bea7389bbb9be4f110e5cbb4 to your computer and use it in GitHub Desktop.
Generic class to parse pipe separated text into object
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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