Complex Linq Query, building the Where Clause

G

Guest

When building a query for the LinkToSql a need to build a where clause that
has both individual values and range selections like this SQL Query:

- WHERE( (IdItem BETWEEN 1 AND 10 OR IdItem = 15 OR IdItem BETWEEN 30 AND
100 OR IdItem = 500... ) AND ( IdMenu BETWEEN 1 AND 5 OR) ...)

How can I write a LINQ statement that makes a efficient query like this?
 
G

Guest

The range and individual values are created at runtime and stored in memory,
so it is the dynamic buildiing of this staement that are a bit tricky.
 
J

Jon Skeet [C# MVP]

The range and individual values are created at runtime and stored in memory,
so it is the dynamic buildiing of this staement that are a bit tricky.

If you build it up using extension methods directly instead of a query
expression, it's not too bad:

var query = dataContext.WhicheverTable; // The source part

if (restrictByFirstCriterion)
{
query = query.Where(item => item.Foo > wibble);
}
if (restrictBySecondCriterion)
{
query = query.Where(item => item.Bar < 0);
}
etc

Basically keep applying Where clauses (or others, such as joins) as
appropriate.

Jon
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top