I have an extension method :
public static List<object> ToModelViewObjectList<ModelViewType>(this IEnumerable<object> source)
{
    List<ModelViewType> destinationList = new List<ModelViewType>();
    PropertyInfo[] ModelViewProperties = typeof(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((ModelViewType)destElement);
    }
    return destinationList.Cast<object>().ToList();
}
And I have a method with a list of object that I want call extension methods in this method :
public void GridModel(IEnumerable<object> GridDataSource)        
{ 
   List<object> list = GridDataSource.ToModelViewObjectList<GridDataSource[0].GetType()>();
}
What should I write instead of GridDataSource[0].GetType() ?
I have a method with a object parameter. I want to create a generic list of object type.
public void CreateListByNonGenericType(object myObject)
{
    Type objType = myObject.GetType();
    var lst = System.Collections.Generic.List < objType.MakeGenericType() > ();
}
What should I write instead of objType.MakeGenericType() ?
public void CreateListByNonGenericType(object myObject)
{
    Type objType = myObject.GetType();
    Type listType = typeof(List<>).MakeGenericType(objType);
    //We can not use here generic version of the interface, as we
    // do not know the type at compile time, so we use the non generic 
    // interface IList which will enable us to Add and Remove elements from
    // the collection
    IList lst = (IList)Activator.CreateInstance(listType);
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With