相关主题:
Create Expression<Func<T, TKey>>
dynamically
我在互联网上搜索但所有样本都解释了 Expression<Func<
.我如何动态创建 Func<T, TKey>
来自 T
?
谢谢
编辑 1)
T
输入我的代码在运行时确定,例如我想用 Name
对我的列表进行排序.现在我如何创建它:Func<T, TKey> = o=>o.Name;
编辑 2)
请考虑一下:
public abstract class MyClass<T> where T : class
{
public virtual List<T> GetAll(Expression<Func<T, bool>> exp, string orderByProperty)
{
repository.Get(exp).OrderBy(?);
}
}
问题是创建一个 Func<T, TKey>
用于 OrderBy
争论。如何使用 Name
对列表进行排序属性(property)?
谢谢
最佳答案
鉴于抽象类的定义,您需要将键包含在通用参数中以便能够使用它。
通过函数传递订单的简单示例。
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();
}
}
然后您可以拥有具有默认键类型的类的派生版本
例如,下面使用了一个 string
,但它也可以很容易地成为一个 int
、Guid
等。
public abstract class MyClass<T> : MyClass<T, string> where T : class {
}
但最重要的是,您需要知道按类型排序才能使用它。
...GetAll(_ => _.SomeProperty == someValue, o => o.Name);
关于func - 动态创建 Func<T, TKey>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55793347/