Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Possible to ignore the Expression if it's null or empty without checking for null in an IF statement?

Well, I have two expression X , Y

if flag is true then y has a expression

I need a List<mylist> v = list.where(x).where(y).ToList();

In this case if the y expression is null, it will throw an exception,

I know I can check for null before building the query, but in a huge query this can be a nightmare.

So is there any way or a value to tell the expression to be ignored when executing the expression ?

like image 239
Kas Avatar asked Dec 08 '22 11:12

Kas


1 Answers

You can add your own extension methods easily enough. It's not immediately clear whether you're using IQueryable<> or IEnumerable<> (your code wouldn't compile either way, due to casing issues and the fact that no Where method returns List<T>, and the fact that you're using x in the same statement you're declaring it) but you can handle both easily:

public static class NullSafeExtensions
{
    public static IEnumerable<T> NullSafeWhere<T>(this IEnumerable<T> source,
        Func<T, bool> predicate)
    {
        return predicate == null ? source : source.Where(predicate);
    }

    public static IQueryable<T> NullSafeWhere<T>(this IQueryable<T> source,
        Expression<Func<T, bool>> predicate)
    {
        return predicate == null ? source : source.Where(predicate);
    }
}

Then:

var results = source.NullSafeWhere(x).NullSafeWhere(y);

(Of course, it's only null-safe in terms of the predicate, not the source...)

like image 118
Jon Skeet Avatar answered Dec 11 '22 01:12

Jon Skeet