writing linq query with varying search criteria


  • Hello,

    I have an interesting problem to do with filtering linq results and I'm wondering if there's a way to do this.

    First, I am given a string of search filters of the form:

    "(x and y and z) or (a and b and c) or..."

    Then I have an IEnumerable like so:

    var result = context.GetResults();

    The challenge is to use the search filter string on result using linq. With the above search filter string, the linq query would be:

    return result.Where(d => (d.description.Contains(x) && d.description.Contains(y) && d.description.Contains(z))
    || (d.description.Contains(a) && d.description.Contains(b) && d.description.Contains(c)));

    However, I'm not always going to get that exact search filter string. I may get this:

    "(x and y) or (z)"

    or this:

    "(x) or (y) or (z)"

    or this:

    "(x and y and z and a)"

    Can anyone think of a way to write a generic linq query that can handle varying ands/ors between the search keywords?

    Thursday, February 16, 2017 10:23 PM

All replies

  • Hi gib898,

    You may have a wrong logic.  Linq cannot help you make a condition to judge. You should make this  filter  condition use a if,,, else statement.

    Best regards,


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact

    Friday, February 17, 2017 9:11 AM
  • If x,y and z are names of fields/members on the object you're using LINQ for then convert it to a lambda expression. There are several libraries available that do this. Alternatively you could spin up the CSharpCodeProvider and basically do the same thing. None of this will be fast though.

    Yet another option is to build a simple parser that understands the syntax you'll allow and generates the appropriate LINQ statements.

    Michael Taylor

    Friday, February 17, 2017 3:06 PM
  • If your filters are known at development time, then, you just needt to write the proper code.

    If your filters are known ONLY at runtime, then, there is no chance, because the assembly created is IMMUTABLE, therefore you cannot add names or code into it, besides many other things.

    That said, parsing the *filter* object is not an option, because at development time you need to know how to parse that object. This means you need to write an SPECIFICATION related to tbis object telling its syntax, semantics, rules, etc... If you do this, then you'll be able to write at development time a parser, to parse such objects.

    One possible solution for you, is define a group of possiblend fixed filters, that the user can choose at runtime, and write the code, at development time, for each one of those filters.

    Friday, February 17, 2017 6:40 PM