Ketchup
Ketchup

Reputation: 3111

Using method parameter as generic type argument

I have a class (SearchParameters) that holds search parameters, i then create a linq query based on these using a generic class called Querybuilder. This returns the results and all works perfectly.

The results are displayed in GridView, i am currently implementing custom sorting for the gridivew, I add the field to be searched to the SearchParameters object (using a fluent interface)

SearchParameters=SearchParameters.SortResultsBy(e.SortExpression,e.NewSortOrder.ToString());

I need the datatype of the columns to be used as a generic parameter to my AddOrderByClause() method:

    public void AddOrderByClause<D>(string field, Type sourceDateType)
    {
        var orderExpression = Expression.Lambda<Func<T, D>>(Expression.Property(resultExpression, field), resultExpression);

        rootExpression = Expression.Call(
              typeof(Queryable),
              "OrderBy",
              new Type[] { typeof(T), typeof(D) },
       rootExpression,
       orderExpression);

    }

I can easily find the data type of the columns, but how do i pass it to the AddOrderByClause() (generic parameter D)?

Upvotes: 2

Views: 356

Answers (3)

Tilak
Tilak

Reputation: 30698

but how do i pass it to the AddOrderByClause() (generic parameter D)?

Seems like you already have datatype of the columns, and you figuring out how to pass it to Generic method

Below is example

First modify AddOrderByClause to accept T (used later in your function)

public void AddOrderByClause<D,T>(String field)
{
....
}

Then call AddOrderByClause like

 var data = SearchParameter;// Use actual data if SearchParameter is not correct
 AddOrderByClause<D,date.GetType()>(fieldData);// assuming fieldData is something different 
 var data = SearchParameter;// Use actual data if SearchParameter is not currect

Upvotes: 0

McGarnagle
McGarnagle

Reputation: 102743

Use reflection to get the method AddOrderByClause, then use MakeGenericMethod to get the generic. This is the general idea (a bit vague because I don't know what all your types are named).

Type MyTypeParameter;    // TODO set this to type parameter D
Type type;               // TODO set this to the type that contains the method "AddOrderByClause"
MethodInfo method = type.GetMethod("AddOrderByClause");
MethodInfo genericMethod = method.MakeGenericMethod(typeof(MyTypeParameter));
genericMethod.Invoke(MyClassInstance, FieldParam, SourceDataParam);

Upvotes: 0

Kishore Kumar
Kishore Kumar

Reputation: 12864

public void AddOrderByClause<D,E>(string field, E sourceDataType)
{
    .....
}

Upvotes: 1

Related Questions