What should I write instead GridDataSource[0].GetType()?
Since you do not know the type at compile time, you need to execute everything at runtime. Therefore, you need to make a general method from the method definition and call it. Something like the following:
GridModel(IEnumerable<object> GridDataSource)
{
Type dataSourceElementType = GridDataSource[0].GetType();
MethodInfo methodDefinition = typeof(MyExtension).GetMethod("ToModelViewObjectList");
MethodInfo method = methodDefinition.MakeGenericMethod(dataSourceElementType)
List<object> list = (List<object>)method.Invoke(GridDataSource, null);
}
, , - ToModelViewObjectList , , , ModelViewType , . , .
public static List<object> ToModelViewObjectList(this IEnumerable<object> source, Type modelViewType)
{
List<object> destinationList = new List<object>();
PropertyInfo[] ModelViewProperties = modelViewType.GetProperties();
foreach (var sourceElement in source)
{
object destElement = Activator.CreateInstance(modelViewType);
foreach (PropertyInfo sourceProperty in sourceElement.GetType().GetProperties())
{
if (ModelViewProperties.Select(m => m.Name).Contains(sourceProperty.Name))
{
destElement.GetType().GetProperty(sourceProperty.Name).SetValue(destElement, sourceProperty.GetValue(sourceElement));
}
}
destinationList.Add(destElement);
}
return destinationList;
}
, :
List<object> list = GridDataSource.ToModelViewObjectList(GridDataSource[0].GetType());
GridDataSource, - , .