I have this C# code that works just fine, which grabs any two fields and puts them in a list for a Drop Down List:
var myDDL = GetDDLValues<Product>( myContact, "contactid", "companyname");
I would like it to take the two string parameters in something other than strings. This would be really nice to do:
GetDDLValues<Product>( myContact, p => p.contactid, p => p.companyname)
This is the code it calls (reflection by sweko Thanks!):
private object GetProperty(object obj, string propertyName)
{
PropertyInfo pi = obj.GetType().GetProperty(propertyName);
object value = pi.GetValue(obj, null);
return value;
}
public IList<DDLValues> GetDDLValues<T>(IList<T> objectListToMap,
string textProperty, string valueProperty)
{
if( objectListToMap != null && objectListToMap.Count > 0)
{
Mapper.CreateMap< T, DDLValues>()
.ForMember( dest => dest.text,
opt => opt.MapFrom(src => textProperty))
.ForMember( dest => dest.value,
opt => opt.MapFrom(src => valueProperty));
return Mapper.Map<IList<T>, IList<DDLValues>>(objectListToMap);
}
else
{
return null;
}
}