Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 从Func返回Func_C#_Linq - Fatal编程技术网

C# 从Func返回Func

C# 从Func返回Func,c#,linq,C#,Linq,我正在尝试使用动态生成linqtosql查询。在将表达式发送到LinqKit之前,我想检查要为预测添加的字段。所以我想出了一些想法,比如 Expression<Func<TResult, bool>> GetPrediction<TKey> (Expression<Func<TResult, TKey>> selector, TResult input, object valu

我正在尝试使用动态生成linqtosql查询。在将表达式发送到LinqKit之前,我想检查要为预测添加的字段。所以我想出了一些想法,比如

 Expression<Func<TResult, bool>> GetPrediction<TKey>
                            (Expression<Func<TResult, TKey>> selector, TResult input,  object value)
 {
    if(typeof(TKey) == typeof(string))
    {
         return selector.Invoke(input) == value; //Not working, how to covert here?
    }
    Throw new Exception("Type not supported");
 }
Expression-GetPrediction
(表达式选择器、TResult输入、对象值)
{
if(typeof(TKey)=typeof(string))
{
return selector.Invoke(input)=value;//不工作,这里如何转换?
}
抛出新异常(“不支持类型”);
}

我被困在第5行,在那里我应该生成一个表达式
,然后返回。我知道这是可能的,但只是很难得到“点击”按钮,我想你想要的是:

public static Expression<Func<TResult, bool>> GetPredicate<TKey>
    (Expression<Func<TResult, TKey>> selector, TResult input, object value)
{
    // Note: Move "early out" here so that bulk of method is less deeply nested.
    // Really? Why make this generic in TKey then?
    if (typeof(TKey) != typeof(string))
    {
        throw new Exception("Type not supported");
    }

    var parameter = Expression.Parameter("input");
    var invocation = Expression.Invoke(selector, input);
    var constant = Expression.Constant(value);
    var equality = Expression.Equal(invocation, constant);
    return Expression.Lambda<Func<TResult, bool>>(equality, parameter);
}
公共静态表达式GetPredicate
(表达式选择器、TResult输入、对象值)
{
//注意:将“早出”移到这里,这样方法的大部分嵌套就不那么深了。
//真的吗?那为什么要在TKey中使用通用的呢?
if(typeof(TKey)!=typeof(string))
{
抛出新异常(“不支持类型”);
}
var参数=表达式参数(“输入”);
var invocation=Expression.Invoke(选择器,输入);
var常量=表达式常量(值);
var equality=Expression.Equal(调用,常量);
返回表达式.Lambda(等式,参数);
}

我不太确定将使用哪种类型的相等,请注意,它完全可能使用引用相等操作,而我怀疑您希望值相等。您必须尝试查看,由于字符串插入,在测试中要小心。

您遇到了什么错误?从这里的代码中,我可以看到您试图返回bool,而您的方法需要一个表达式……我知道它为什么不起作用。那条线是作为占位符存在的。我真正想回报的是一个表达,但我很难找到答案。我不知道你想做什么。。如果你解释一下最初的问题,也许我能帮上忙。。就像现在一样。。我迷路了,很抱歉失去你。最初的问题是关于使用具有定制行为的LinqKit。非常感谢!早期的部分实际上不仅仅是字符串。我想限制这些类型的原因是,如果我的谓词包含自定义类型,LinqToSql将抛出“无法转换为SQL”异常。所以,我只想要基本类型。
return p => (selector.Compile().Invoke(input) as string) == value