Home All Groups Group Topic Archive Search About

Complex Linq Query, building the Where Clause

Author
18 Oct 2007 9:03 AM
Harald SMS
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?
--
Harald SMS

Author
18 Oct 2007 9:13 AM
Harald SMS
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.
--
Harald SMS


Show quote
"Harald SMS" wrote:

> 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?
> --
> Harald SMS
Author
18 Oct 2007 2:34 PM
Jon Skeet [C# MVP]
On Oct 18, 10:13 am, Harald SMS <Harald***@discussions.microsoft.com>
wrote:
> 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

AddThis Social Bookmark Button