4

I am currently looking for a way where I can build a lambda expression for my Linq to SQL query based on user input at runtime. I have been looking around on the net, but can't find anything that is useful. If anyone can show me how to do this or there is any good articles, please do let me know. Much appreciated!

Example:

Let's say I have this Linq query:

var loc = (from l in Entity.Locations
           select l).Where(a => a.LocationId > 5);

Can this expression a => a.LocationId > 5 be built at runtime? Depending on whether the user has chosen LocationId. If the user has chosen Name then it would be a => a.Name == "bla".

I have come across an article from Scott but I would prefer a solution that allows me to create a strongly type expression which I can detect any possible errors at compile time.

Any information would be much appreciated.

Thanks.

1 Answer 1

2

You can create new LINQ expressions containing old expressions.

var loc = (from l in Entity.Locations select l);

if (hasLocation)
    loc = loc.Where(a => a.LocationId > 5);

if (hasName)
    loc = loc.Where(a => a.Name == "bla");

etc.

The expression is only evaluated once you use it, like var result = loc.ToList();

Sign up to request clarification or add additional context in comments.

1 Comment

cool. Thanks. I was actually thinking of building an expression tree but don't know how to do that. This will do. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.