BradleyUffner

String to Class

Sep 7th, 2017
298
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.36 KB | None | 0 0
  1. static public class StringExtensions
  2. {
  3.     private class TypeData
  4.     {
  5.         public PropertyInfo Prop { get; set; }
  6.         public MethodInfo ParseMethod { get; set; }
  7.     }
  8.  
  9.     private static List<TypeData> FindFields<T>(IEnumerable<string> fields)
  10.     {
  11.         var data = new List<TypeData>();
  12.         var targetType = typeof(T);
  13.  
  14.         foreach (var field in fields)
  15.         {
  16.             var item = new TypeData();
  17.             data.Add(item);
  18.  
  19.             item.Prop = targetType.GetProperty(field, BindingFlags.Public | BindingFlags.Instance);
  20.             var propType = item.Prop.PropertyType;
  21.             item.ParseMethod = propType == typeof(string) ? null : propType.GetMethod("Parse", new[] { typeof(string) });
  22.         }
  23.  
  24.         return data;
  25.     }
  26.  
  27.     public static List<T> StringToList<T>(this string input, IEnumerable<string> fields) where T : new()
  28.     {
  29.         var targetType = typeof(T);
  30.         var fieldData = FindFields<T>(fields);
  31.  
  32.         var list = new List<T>();
  33.         var rawSource = input.Split('\n');
  34.         foreach (var rawLine in rawSource)
  35.         {
  36.             var item = new T();
  37.             list.Add(item);
  38.             var rawFields = rawLine.Split(',');
  39.             int fieldIndex = 0;
  40.             foreach (var field in fieldData)
  41.             {
  42.                 var rawField = rawFields[fieldIndex].Trim();
  43.                 object parsedValue = field.ParseMethod == null ? rawField : field.ParseMethod.Invoke(null, new[] { rawField });
  44.                 field.Prop.SetValue(item, parsedValue);
  45.                 fieldIndex++;
  46.             }
  47.         }
  48.         return list;
  49.     }
  50. }
Advertisement
Add Comment
Please, Sign In to add comment