Related Topics:
Create Expression<Func<T, TKey>>
dynamically
I searched on the internet but all samples explain Expression<Func<
. How I can dynamically create a Func<T, TKey>
from T
?
Thanks
Edit 1)
The T
type in my code determine in runtime and for example I want to sort my list with Name
. Now How I can create this : Func<T, TKey> = o=>o.Name;
Edit 2)
Please consider this:
public abstract class MyClass<T> where T : class
{
public virtual List<T> GetAll(Expression<Func<T, bool>> exp, string orderByProperty)
{
repository.Get(exp).OrderBy(?);
}
}
The problem is create a Func<T, TKey>
for using in OrderBy
argument. How can I sort the list using Name
property?
Thanks
Given the definition of the abstract class, you would need to include the key are part of the generic arguments in order to be able to use it.
Simple example of passing the order by function.
public abstract class MyClass<T, TKey> where T : class {
public virtual List<T> GetAll(
Expression<Func<T, bool>> exp,
Func<T, TKey> keySelector = null
) {
var query = repository.Get(exp);
if(orderBy != null) {
return query.OrderBy(keySelector).ToList();
return query.ToList();
}
}
You could then have a derived version of the class with a default key type
For example, the following uses a string
, but that could just as easily been an int
, Guid
, etc..
public abstract class MyClass<T> : MyClass<T, string> where T : class {
}
But bottom line is you need to know the order by type in order to be able to use it.
...GetAll(_ => _.SomeProperty == someValue, o => o.Name);