开发者

Linq to SQL Where Extension Method Question

The Linq to SQL Where extension method takes, as a parameter, something that looks like this:

Expression<Func<Table,bool>> predicate

Could someone describe, in simple terms, exactly what开发者_运维问答 this statement means? I want to create a method that takes one of these, that I can pass onto an L2S query, and I want to understand exactly what it is, and how it should be called.

Thank you.


The variable type Expression<Func<Table, bool>> means it takes a code expression representing a method/delegate/lambda expression that takes a Table parameter and returns a bool. A method that takes an Expression<> parameter intends to parse the code to generate other code rather than evaluating the 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 into them the same way that you'd pass a lambda expression, but whether your value is interpreted as an Expression or a lambda depends on the signature of the method you're passing it into.

Here's an example of passing an Expression<Func<Table, bool>> into a method (which looks the same as passing a 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's how you'd write your own method that takes one as a parameter and applies it to a L2S query:

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


I am just providing a simple explanation for how expressions work.From the sample code in the example given 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 say you have a function that returns true if no < 5 like -

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

So you can build an expression doing same thing using above syntax and then pass it to say a Where or some thing simliar.Simple example -

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 the parameter so it will take an 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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜