如何实现 Linq NullCheck 表达式?

How to implement a Linq NullCheck Expression?

我很难尝试使用 linq 实现 nullcheck (isNull, isNotNull) 表达式。 这是我的部分代码:

//create a blog collection
var blogsCollection = new List<Blog>();
for (var i = 1; i <= 15; i++)
{
    var b = new Blog()
    {
        BlogId = i,
        Url = $"http://{i}.blog.com",
        CreatedAt = DateTime.UtcNow.AddDays(-i),
    };
    blogsCollection.Add(b);
}

ParameterExpression parameterExpression = Expression.Parameter(typeof(Blog), "item");
Expression propertyExpression = Expression.Property(parameterExpression, "BlogId");
Expression targetExpression = Expression.Constant(null, propertyExpression.Type);
Expression exp = Expression.Equal(propertyExpression, targetExpression);
var filter=Expression.Lambda<Func<Blog, bool>>(exp, parameterExpression).Compile();
var blogs = (List<Blog>)blogsCollection.Where(filter);

此代码抛出异常: 参数类型不匹配

如果我将 targetExpression 更改为(不进行类型转换): 表达式 targetExpression = Expression.Constant(null);

然后它抛出一个不同的异常: System.InvalidOperationException : 二元运算符 Equal 没有为类型 'System.Int32' 和 'System.Object'

定义

关于如何在 Linq 中进行空检查的任何想法?我已经在此处检查过,但其中 none 似乎有效。

您的 Id 属于 System.Int32 类型,它是一个值类型,因此它始终不为空(即 BlogId == null 始终为 false)。如果你想实现一个支持所有可能输入的通用过滤器,你可以这样做:

if (propertyExpression.Type.IsValueType && Nullable.GetUnderlyingType(propertyExpression.Type) == null)
{
    filter = Expression.Lambda<Func<Blog, bool>>(Expression.Constant(false), parameterExpression).Compile();
}
else
{
    // your current code
}