Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 642311
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 13, 20262026-05-13T21:09:26+00:00 2026-05-13T21:09:26+00:00

I’m writing a bit of LINQ to SQL that needs to perform a search

  • 0

I’m writing a bit of LINQ to SQL that needs to perform a search for client information in our database, filtering the results and paging them. The filtering needs to be dynamic so I have broken the setup of the query into four stages:

  1. Find visible clients (basically apply a coarse grained filter)
  2. Filter clients by search criteria
  3. Sort and page the clients
  4. Retrieve additional client data

The code goes along the lines of:

// Step 1
var visibleClientQuery = from x in xs
                         from y in ys
                         from z in yas
                         where
                             ...
                         select new
                         {
                             id = z.Client.Id,
                             a = z.Client.a,
                             b = z.Client.e.f.g.b
                         };

// Step 2
if (filterByA)
{
    visibleClientQuery = visibleClientQuery.Where(client => client.a > 10);
}
else
{
    visibleClientQuery = visibleClientQuery.Where(client => client.b.StartsWith("ABC"));
}

// Step 3
visibleClientQuery = visibleClientQuery.Distinct();

if (filterByA)
{
    visibleClientQuery = visibleClientQuery.OrderBy(client => client.a);
}
else
{
    visibleClientQuery = visibleClientQuery.OrderBy(client => client.b);
}

visibleClientQuery = visibleClientQuery.Skip(50).Take(30);

// Step 4
var fullQuery = from filterClientDetail in filteredClientQuery
                 join client in Clients on filterClientDetail.Id equals client.Id
                 ...;

LINQ to SQL does a great job of combining these elements together to produce an efficient query. But one thing I want to do is reduce the number of joins created in the first, coarse query. If I’m filtering and sorting by A, there is no need for the first query to populate b using the line:

b = z.Client.e.f.g.b

Not populating b would save all that extra joining. I tried replacing the line with:

b = filterByA ? string.Empty : z.Client.e.f.g.b

Whilst this functionally works, when filterByA is true, the excess joins are still present in the query… slowing it down. My workaround is to introduce another interim query that wraps the Step 1 query:

// Step 1
var visibleClientQuery = from x in xs
                         from y in ys
                         from z in yas
                         where
                             ...
                         select z.Client;

// Step 2
var filteredClientQuery = from client in visibleClientQuery
                          select new
                          {
                              id = client.Id,
                              a = client.a,
                              b = string.Empty
                          };

Then if we need to filter by B, this is replaced with:

filteredClientQuery = from client in visibleClientQuery
                      select new
                      {
                          id = client.Id,
                          a = 0,
                          b = client.e.f.g.b
                      };

So long as the replacement query returns an anonymous class with the same properties, this works, but seems like an unnecessary, heavyweight hack and doesn’t allow easy mixing and matching of filters… what if we need to filter by A and B? The real query has several more possible filters.

Is there any way to programtically change how an individual property is populated within the anonymous class returned from a query… in much the same way that the where clause can be changed? Using filteredClientQuery.Select(…) I can swap out the entire select, but I can’t see a way to work on an individual property.

Any help appreciated… even if it is to just confirm there is no solution!

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-13T21:09:26+00:00Added an answer on May 13, 2026 at 9:09 pm

    So after rejecting the use of strings and deciding that manually building the expression was going to be way to complex (thanks David B for your efforts there) I decided to give LinqKit a go. This is based on some cool code written by Tomas Petricek. I had a couple of false starts but within 30 minutes it was all working exactly as I hoped. I now have code approximately like this:

    // Step 1
    var visibleZQuery = from x in xs.AsExpandable()
                             from y in ys
                             from z in yas
                             where
                                 ...
                             select Z;
    
    // Step 2
    if (filterByA)
    {
        visibleZQuery = visibleZQuery.Where(client => client.a > 10);
    }
    
    if (filterByB)
    {
        visibleZQuery = visibleZQuery.Where(client => client.b.StartsWith("ABC"));
    }
    
    Expression<Func<Z, string>> aSelector = z => string.Empty;
    Expression<Func<Z, string>> bSelector = z => string.Empty;
    
    if (filterByA)
    {
        aSelector = z => z.Client.a;
    }
    
    if (filterByB)
    {
        bSelector = z => z.Client.e.f.g.b;
    }
    
    var filteredClientQuery = from z in visibleZQuery
                              select new 
                              { 
                                  id = z.Client.Id, 
                                  a = aSelector.Invoke(z), 
                                  b = aSelector.Invoke(z)
                              }; 
    
    // Step 3
    filteredClientQuery = filteredClientQuery.Distinct();
    
    if (filterByA)
    {
        filteredClientQuery = filteredClientQuery.OrderBy(client => client.a);
    }
    else if (filterByB)
    {
        filteredClientQuery = filteredClientQuery.OrderBy(client => client.b);
    }
    
    filteredClientQuery = filteredClientQuery.Skip(50).Take(30);
    
    // Step 4
    var fullQuery = from filterClientSummary in filteredClientQuery
                     join client in Clients on filterClientSummary.Id equals client.Id
                     ...;
    

    There are a few changes to the code but the most significant is that the first query uses AsExpandable() to introduce the LinqKit wrapper and the select statement in Step 2 is populated with expressions that are defined outside of the construction of the main query. Everything is type safe and, apart from the AsExpandable(), the rest of the code works much as a developer who is used to Linq to SQL would expect.

    I confirmed that this approach still appears to create efficient SQL that now only joins to tables if they are actually required.

    Thanks to Timores and David B for your input!

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I have a view passing on information from a database: def serve_article(request, id): served_article
link Im having trouble converting the html entites into html characters, (&# 8217;) i
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I've got a string that has curly quotes in it. I'd like to replace
I have a French site that I want to parse, but am running into
I am doing a simple coin flipping experiment for class that involves flipping a
We're building an app, our first using Rails 3, and we're having to build
This could be a duplicate question, but I have no idea what search terms

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.