Linq to SQL Where is the extension method question

Linq to SQL Where the extension method accepts something like this as a parameter:

Expression<Func<Table,bool>> predicate 

Can someone just describe what that means? I want to create a method that accepts one of them that I can pass to an L2S request, and I want to understand exactly what it is and how it should be called.

Thanks.

+4
source share
2 answers

The type of the variable Expression<Func<Table, bool>> means that it accepts a code expression representing the expression method / delegate / lambda, which takes the Table parameter and returns bool . The method that accepts the Expression<> parameter is designed to analyze the code to generate other code, and not to evaluate Expression itself. LINQ to SQL can use them to generate SQL code to do what your code represents.

The strange thing about Expression<> parameters is that you pass values ​​to them in the same way you would pass a lambda expression, but whether your value is understood as Expression or lambda depends on the signature that you pass.

Here's an example of passing Expression<Func<Table, bool>> to a method (which looks the same as passing the Func<Table, bool> parameter:

 theMethod(table => table.NumLegs > 3); // or to be more explicit: theMethod((Table table) => table.NumLegs > 3); // or... theMethod(delegate(Table table) { return table.NumLegs > 3; } ); 

Here you must write your own method that takes one parameter and applies it to the L2S request:

 IQueryable<Table> addWhereClause( IQueryable<Table> tables, Expression<Func<Table, bool>> whereClause) { return tables.Where(whereClause); } 
+4
source

I just provide a simple explanation of how expressions work. From the sample code in the example below, here is an example -

 System.Linq.Expressions.Expression<Func<int, bool>> expr = i => i < 5; // Compile the expression tree into executable code. Func<int, bool> deleg2 = expr.Compile(); // Invoke the method and print the output. Console.WriteLine("deleg2(4) = {0}", deleg2(4)); //OUTPUT : deleg2(4) = True 

So, in simple words, we say that you have a function that returns true if no <5 like -

 Func<int, bool> deleg = i => i < 5; 

So you can create an expression using the same thing using the syntax above and then pass it in to say a Where or some simlyar thing. A simple example is

 int[] i={1,2,3,4,5} System.Linq.Expressions.Expression<Func<int, bool>> expr = i => i < 5; var result=i.Where(expr);//equivalent to i.Where(c=>c<5) 

In your case, you have a table as a parameter, so it will take a table object and return bool.

 List<Employee> e= new List<Employee>(); e.Add(new Employee(1,"ABC",5000)); e.Add(new Employee(2,"ACC",5000)); e.Add(new Employee(3,"ADC",50009)); System.Linq.Expressions.Expression<Func<Employee, bool>> expr =e => e.Salary < 50000; var result=e.Where(expr);//give all employee with salary<50000 
+1
source

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


All Articles