Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How define a generic type from an object type?

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() ?

Edited:

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() ?

like image 640
Siamak Ferdos Avatar asked Dec 12 '22 02:12

Siamak Ferdos


1 Answers

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);
}
like image 166
hazzik Avatar answered Dec 29 '22 09:12

hazzik