Using LINQ Queries, but making very flexible

I am curious how I can go about doing the following. I am creating an application that is similar to the custome data filter on excel. Here is an example of how the custom data filter would work:

If (Column A) "is greater than" 0


If (Column B) "is greater than" 0

A similar query in LINQ would look like:

var query = from s in CurrentDataContext.TableA
                   where (s.ColumnA > 0) && (s.ColumnB > 0)
                   select s;

The problem I am having is that the user is more or less setting its own rules, with an infanite number of conditions. Therefore, I cannot set a query for each possible query. I need to somehow use loops or just in general make it flexible enough to be able to do this.

Does anyone know how I can do that? If I need to elaborate, please let me know.

Who is Participating?

[Webinar] Streamline your web hosting managementRegister Today

dstanley9Connect With a Mentor Commented:
If you can build your conditions into strings you would call the .Where method rather than the Ling syntactic sugar:

string condition = "ColumnA > 0 && ColumnB > 0";

var query = CurrentDataContext.TableA

Here's some other examples:
A better way is to use the predicate builder in the free library LinqKit because that way you don't loose the advandage of code completion and checking (

IQueryable<Product> SearchProducts (params string[] keywords)
  var predicate = PredicateBuilder.False<Product>();

  foreach (string keyword in keywords)
    string temp = keyword;
    predicate = predicate.Or (p => p.Description.Contains (temp));
  return dataContext.Products.Where (predicate);

The above example uses OR to combine the conditions, but it you can easily construct an AND condition :

var predicate = PredicateBuilder.True<Product>();

if (a!=null)
  predicate = predicate.And( p => p.Description==a);

if (b!=null)
  predicate = predicate.And(p=>p.Category==b);

P.S. you can use there free tool LinqPad to test the queries
All Courses

From novice to tech pro — start learning today.