func - 动态创建 Func<T, TKey>

标签 func dynamic-linq c#-7.0

相关主题:

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,但它也可以很容易地成为一个 intGuid 等。

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/

相关文章:

swift - 如何在 Swift 中声明一个元组并为其成员之一提供运行时函数

c# - 如何在 SimplSocket(Func<System.IO.Sockets.Socket> socketFunc) 中调用以下构造函数 Func<T>

c# - 重复调用HashCode.Combine

C#7 值元组/解构不对称

c# - 对于 Func<T, TResult>,其中 A extends T,A 不满足 T

c# - 合并两个相同类型的表达式(没有 bool 值)

LINQ:在运行时构建 where 子句以包含 OR( || )?

.net - dynamic-linq Select 中的字符串连接

c# - 在动态 Linq 查询中嵌套 OrderBy 如何工作?

c# - 为什么在 lambda 中抛出异常是 C# 7 的一个特性?