Linq expression that would always return true

I need to pass a parameter to a method that requires Expression<Func<T, bool>> .

How do I pass an expression that will always return true ?

Using obj => true does not work because the structure complains at runtime that it cannot determine the memeber type from the True constant.

+5
source share
4 answers

If you have such a function,

 void TakeExpression<T>(Expression<Func<T, bool>> expr) 

You should call it this by specifying type T:

 TakeExpression<int>(_ => true) 

It should work.

+11
source

You need to determine the type of parameter you are passing:

 (object o) => true 

or

 (int a) => true 
+1
source

We can achieve the result as follows.

Consider context as an instance of DbContext, and Entity as the name of an entity class.

 context.Entity.Where(t=> t.EntityID == t.EntityID); 

In this case, the where clause will always return true and all data will be displayed.

0
source

There are two problems here:

1) If you pass the predicate in such a way that you always want to return true, then this is not so much a predicate. You may be able to omit any call you are trying to make.

2) If you want to simply return true, you can simply use the more detailed lambda syntax to get what you want:

 sample.AsQueryable().Where((x) => { return true; }); 

More detailed syntax allows you to specify closer to an anonymous function, while still being an expression.

-1
source

Source: https://habr.com/ru/post/1346044/


All Articles