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 ?
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...)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With