/// <summary>
/// Converts an ubiquitous enumeration of series to a strongly typed enumeration by matching property names.
/// </summary>
/// <typeparam name="T">Type to convert the enumeration of series to</typeparam>
/// <param name="series">Series to convert</param>
/// <returns>Strongly typed enumeration representing the series</returns>
public static IEnumerable<T> As<T>(this IEnumerable<Serie> series) where T : new()
{
if (series == null)
yield return default(T);
Type type = typeof(T);
foreach (var serie in series)
{
var properties = type.GetProperties(BindingFlags.Instance | BindingFlags.Public).ToList();
var matchedProperties = serie.Columns
.Select(columnName => properties.FirstOrDefault(
property => String.Compare(property.Name, columnName, StringComparison.InvariantCultureIgnoreCase) == 0))
.ToList();
foreach (var value in serie.Values)
{
var instance = new T();
for (var columnIndex = 0; columnIndex < serie.Columns.Count(); columnIndex++)
{
var prop = matchedProperties[columnIndex];
if (prop == null)
continue;
Type propType = prop.PropertyType;
var convertedValue = Convert.ChangeType(value[columnIndex], prop.PropertyType);
prop.SetValue(instance, convertedValue);
}
yield return instance;
}
}
}
after
/// <summary>
/// Converts an ubiquitous enumeration of series to a strongly typed enumeration by matching property names.
/// </summary>
/// <typeparam name="T">Type to convert the enumeration of series to</typeparam>
/// <param name="series">Series to convert</param>
/// <returns>Strongly typed enumeration representing the series</returns>
public static IEnumerable<T> As<T>(this IEnumerable<Serie> series) where T : new()
{
if (series == null)
yield return default(T);
Type type = typeof(T);
foreach (var serie in series)
{
var properties = type.GetProperties(BindingFlags.Instance | BindingFlags.Public).ToList();
var matchedProperties = serie.Columns
.Select(columnName => properties.FirstOrDefault(
property => String.Compare(property.Name, columnName, StringComparison.InvariantCultureIgnoreCase) == 0))
.ToList();
foreach (var value in serie.Values)
{
var instance = new T();
for (var columnIndex = 0; columnIndex < serie.Columns.Count(); columnIndex++)
{
var prop = matchedProperties[columnIndex];
if (prop == null)
continue;
Type propType = prop.PropertyType;
object convertedValue;
if (propType.IsEnum)
{
convertedValue = Enum.ToObject(propType, value[columnIndex]);
}
else
{
convertedValue = Convert.ChangeType(value[columnIndex], prop.PropertyType);
}
prop.SetValue(instance, convertedValue);
}
yield return instance;
}
}
}
before
after