Kas
Kas

Reputation: 3923

How to store pieces of Linq expression in variables and use those variables in a query?

I have an expression like this:

List<BAL.Receipt> ac = BAL.ApplicationInfo.db.Receipts.Where
                (x => x.InvoiceNo.StartsWith(txtSearch.Text)
                 | x.Alias.StartsWith(txtSearch.Text)

What I want to do is split this expression into parts and store them in variables

Like

var a = x => x.InvoiceNo.StartsWith(txtSearch.Text);
var b = x => x.Alias.StartsWIth (txtSearch.Text) ; 

When query

List<BAL.Receipt> ac = BAL.ApplicationInfo.db.Receipts.Where( a & b) ; 

Is it possible to achieve this?

If possible, please show me an example.

Upvotes: 3

Views: 3653

Answers (1)

Enigmativity
Enigmativity

Reputation: 117064

You should be able to do it like this:

Expression<Func<BAL.Receipt, bool>> a =
    x => x.InvoiceNo.StartsWith(txtSearch.Text);

Expression<Func<BAL.Receipt, bool>> b =
    x => x.Alias.StartsWIth(txtSearch.Text);

List<BAL.Receipt> ac =
    BAL.ApplicationInfo.db.Receipts
        .Where(a)
        .Where(b);

Upvotes: 8

Related Questions