lundi 16 janvier 2017

Reflection inside linq not setting properties

I have the following method to create objects from a delimited file:

public T Map(string line, char delimitter)
{
    if(String.IsNullOrEmpty(line))
        throw new ArgumentNullException(nameof(line));

    if (Char.IsWhiteSpace(delimitter))
        throw new ArgumentException(nameof(delimitter));

    var splitString =  line.Split(delimitter);

    var properties = typeof(T).GetProperties();

    if(properties.Count() != splitString.Count())
        throw new InvalidOperationException($"Row has {splitString.Count()} columns but object has {properties.Count()}.");

    var obj = Activator.CreateInstance<T>();

    for (var i = 0; i < splitString.Count(); i++)
    {
        var prop = properties[i];
        var propType = prop.PropertyType;
        var valType = Convert.ChangeType(splitString[i], propType);
        prop.SetValue(obj, valType);
    }

    return (T)obj;
}

This works as I would expect when calling from a normal method and would create an object from a delimited line. However when run from the following linq statment it doesn't set the property values and just returns null for all properties on the object:

if(hasHeader)
    return File.ReadAllLines(filePath)
               .Skip(1)
               .Select(x => _mapper.Map(x, ','));

return File.ReadAllLines(filePath)
               .Select(x => _mapper.Map(x, ','));





Aucun commentaire:

Enregistrer un commentaire