C# 具有可空类型的LINQ表达式和ALSO

C# 具有可空类型的LINQ表达式和ALSO,c#,linq,C#,Linq,我正在使用LINQ表达式生成一个where条件 我的实体如下: public class Sample { public int Id { get; set; } public string Name { get; set; } public int AnotherId { get; set; } public int? RelationId { get; set; } } 我必须根据两个键过滤数据,即AnotherId和RelationId.RelationI

我正在使用LINQ表达式生成一个
where
条件

我的实体如下:

public class Sample
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int AnotherId { get; set; }
    public int? RelationId { get; set; }
}
我必须根据两个键过滤数据,即
AnotherId
RelationId.RelationId
(可选)。因此,在我的方法中,参数
relationId
可能不会更新并且为0

基于此,我需要生成一个表达式:

Expression<Func<Sample, bool>> condition = x => x.AnotherId == anotherId;
if (relationId > 0)
{
    Expression<Func<Sample, bool>> additionalCondition = x => x.RelationId == relationId;
    condition = Expression.Lambda<Func<Sample, bool>>(Expression.AndAlso(condition, additionalCondition), condition.Parameters);
}
表达式条件=x=>x.AnotherId==AnotherId;
如果(关系ID>0)
{
表达式additionalCondition=x=>x.RelationId==RelationId;
condition=Expression.Lambda(Expression.AndAlso(condition,additionalCondition),condition.Parameters);
}
在这里,我在
语句中得到了以下异常:

未为类型“System.Func``2[Sample,System.Boolean]”和“System.Func`2[Sample,System.Boolean]”定义二进制运算符AndAlso

请帮我纠正我的问题。

这应该可以

if(!(relationId>0))
{ 
  Expression<Func<Sample, bool>> condition = x => x.AnotherId == anotherId;
} else {
  Expression<Func<Sample, bool>> condition = x => x.AnotherId == anotherId && x.RelationId == relationId;
}

正如其他人可能指出的那样,最简单的方法是

x => x.AnotherId == anotherId && (relationId <= 0 || x.RelationId == relationId);

选中linkI think
condition=Expression.Lambda(Expression.AndAlso(condition.Body,additionalCondition.Body),condition.Parameters)
应该可以工作,只是
x.AnotherId==AnotherId&&(!relationId>0 | | x.relationId==relationId)
?@kienct89我检查并添加了扩展方法,但过滤器不工作。@RobertMcKee它工作得很好。一个小变化x.AnotherId==AnotherId&(!(relationId>0)| | x.relationId==relationId)。但是为什么这个表达方法不起作用呢?
var query = something.Where(x=>x.AnotherId == anotherId);
if (relationId>0)
{
  query = query.Where(x=>x.RelationId == relationId);
}
x => x.AnotherId == anotherId && (relationId <= 0 || x.RelationId == relationId);
ParameterExpression param = Expression.Parameter(typeof(Sample), "x");
var anotherIdParam = Expression.Property(param, "anotherId");
var condition = Expression.Equal(anotherIdParam, Expression.Constant(anotherId));

if (relationId > 0)
{
    var relationIdParam = Expression.Property(param, "relationId");
    var additionalCondition = Expression.Equal(relationIdParam, Expression.Convert(Expression.Constant(relationId), typeof(Nullable<int>)));
    condition = Expression.AndAlso(condition, additionalCondition);
}

var finalExpression = Expression.Lambda<Func<Sample, bool>>(condition, param);