Question

I have a simple question but I'm on it since this morning...

How can I init a List<T> without to know its type ? Or (maybe it's more simple) Can I do an OrderBy on a GridView.DataSource ?

Here my code at this moment :

Type type = (from asm in AppDomain.CurrentDomain.GetAssemblies()
             from item in asm.GetTypes() 
             where item.IsClass && item.Name.Equals(myType) 
             select item).Single();
PropertyInfo property = type.GetProperty(myProperty);

this.DataSource = ((List<object>)this.DataSource)
                  .ConvertAll(item => Convert.ChangeType(item, type))
                  .OrderBy(item => type.InvokeMember(property.Name, BindingFlags.GetProperty, null, item, null));

Any suggestions are welcome :)

Edit : Maybe I need to tell you that the first cast (List<object>)this.DataSource fails and I need something for write (List<myType>)this.DataSource instead.

Était-ce utile?

La solution

Assuming that you are implementing IConvertible for the item's type, this should work:

this.DataSource = ((IEnumerable<object>)this.DataSource).ToList()
    .ConvertAll(item => Convert.ChangeType(item, type))
    .OrderBy(item => property.GetValue(item));

Autres conseils

An alternative way to Alex Filipovici's would be using a generic method and expression:

public class Shadam
{
    object DataSource { get; set; }
    public void OrderList(string myType, string myProperty)
    {
        Type type = (from asm in AppDomain.CurrentDomain.GetAssemblies()
                     from item in asm.GetTypes()
                     where item.IsClass && item.Name.Equals(myType)
                     select item).Single();

        var property = type.GetProperty(myProperty);
        typeof(Shadam).GetMethod("OrderGenericList")
                      .MakeGenericMethod(type, property.PropertyType)
                      .Invoke(this, new[] { property });
    }

    public void OrderGenericList<T, TProperty>(PropertyInfo property)
    {
        var tParameter = Expression.Parameter(typeof(T));
        var orderExpression = Expression.Lambda<Func<T, TProperty>>(
                                  Expression.Property(tParameter, property),
                                  tParameter
                              ).Compile();

        this.DataSource = ((List<T>)this.DataSource).OrderBy(orderExpression);
    }
}

It's not easier to order the list before assigning the datasourde? Or using GridView.Sort?

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.sort.aspx

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top