Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- static public class StringExtensions
- {
- private class TypeData
- {
- public PropertyInfo Prop { get; set; }
- public MethodInfo ParseMethod { get; set; }
- }
- private static List<TypeData> FindFields<T>(IEnumerable<string> fields)
- {
- var data = new List<TypeData>();
- var targetType = typeof(T);
- foreach (var field in fields)
- {
- var item = new TypeData();
- data.Add(item);
- item.Prop = targetType.GetProperty(field, BindingFlags.Public | BindingFlags.Instance);
- var propType = item.Prop.PropertyType;
- item.ParseMethod = propType == typeof(string) ? null : propType.GetMethod("Parse", new[] { typeof(string) });
- }
- return data;
- }
- public static List<T> StringToList<T>(this string input, IEnumerable<string> fields) where T : new()
- {
- var targetType = typeof(T);
- var fieldData = FindFields<T>(fields);
- var list = new List<T>();
- var rawSource = input.Split('\n');
- foreach (var rawLine in rawSource)
- {
- var item = new T();
- list.Add(item);
- var rawFields = rawLine.Split(',');
- int fieldIndex = 0;
- foreach (var field in fieldData)
- {
- var rawField = rawFields[fieldIndex].Trim();
- object parsedValue = field.ParseMethod == null ? rawField : field.ParseMethod.Invoke(null, new[] { rawField });
- field.Prop.SetValue(item, parsedValue);
- fieldIndex++;
- }
- }
- return list;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment