Пример #1
0
        public static object MapToObjectProperties(this string[] values, Type type, ColumnIndexToPropertyNameMapping propertiesMapping)
        {
            if (type == null)
            {
                throw new ArgumentNullException(nameof(type));
            }

            if (propertiesMapping == null)
            {
                throw new ArgumentNullException(nameof(propertiesMapping));
            }

            if (values == null || values.Length < 1)
            {
                return(type.Default());
            }

            int numberOfItems = values.Length;

            var result = Activator.CreateInstance(type);

            foreach (var property in type.GetProperties())
            {
                if (propertiesMapping.Mapping.Keys.Contains(property.Name))
                {
                    int index = propertiesMapping.Mapping[property.Name];
                    if (numberOfItems <= index || index < 0)
                    {
                        throw new IndexOutOfRangeException("Invalid mapping.");
                    }

                    var propertyType = property.PropertyType;
                    try
                    {
                        object value = values[index];
                        if (propertyType != typeof(string))
                        {
                            value = values[index].ConvertTo(propertyType);
                        }

                        property.SetValue(result, value, null);
                    }
                    catch (Exception e)
                    {
                        throw new NotSupportedException($"Cannot convert from string to {propertyType}.", e);
                    }
                }
            }

            return(result);
        }
Пример #2
0
        public void CsvMapper_MapOneRowCsvToObject_Generic_ShouldWork()
        {
            const string CsvText = "Name,Year,Description\nJohn Smith,2015,No desription here";

            var csv    = new CsvTableReader();
            var csvRow = csv.ReadToTable(CsvText).Skip(1).ToArray()[0];

            var mapping = new ColumnIndexToPropertyNameMapping
            {
                Mapping = new Dictionary <string, int>
                {
                    { "Name", 0 },
                    { "Year", 1 },
                    { "Description", 2 }
                }
            };

            var result = csvRow.MapToObjectProperties <NameYearDescriptionSampleObject>(mapping);

            Assert.AreEqual("John Smith", result.Name, "Name should match.");
            Assert.AreEqual(2015, result.Year, "Year should match.");
            Assert.AreEqual("No desription here", result.Description, "Description should match.");
        }
Пример #3
0
 public static T MapToObjectProperties <T>(this string[] values, ColumnIndexToPropertyNameMapping propertiesMapping)
 {
     return((T)values.MapToObjectProperties(typeof(T), propertiesMapping));
 }