Click here to Skip to main content
15,887,404 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a LinQ query as below
SQL
var filtered=from c in country
         where c.Id>=5
         select c;


Now i need to have the operator '>=' to be dynamic i.e., the operator may be '>=' or '==' or '<=' etc depending on a certain criteria and the query should execute based on that operator. How to achieve this in LinQ?
Posted

Hi,

You could add a check-function which returns a bool.
Something like this:

C#
private bool TestValue(int id, int contiditon)
{
    if (condition == 1)
    {
        return id <= 5;
    }
    else
    {
        return id >= 5;
    }
}

/* your linq query would look like this */
var filtered = from c in country
               where TestValue(c.Id, c.Condition)
               select c;


This is completely untested so it could contain errors ;)
Hope this helps.

Best regards and happy coding,
Stops
 
Share this answer
 
Comments
abi1988 19-Jul-11 3:20am    
@sTOPs:Thanks for the reply. I know to use an if..else or select..case for this scenario. I need to minimize the code by doing something else from the above mentioned techniques.So, is there any other possibilities?
Christoph Keller 19-Jul-11 3:25am    
You could write it this way:

var filtered = from c in country
where (c.Condition == 1 && c.Id >= 5) ||
(c.Condition != 1 && c.Id <= 5)
select c;

so first check for the condition and combine it (by using '&&') with the second check.

As far as I know, there is no possibility to have a "dynamic" check, whathever this means. The check must be defined somewhere so it is always static.

Hope this helps.
abi1988 19-Jul-11 3:42am    
Yes..this technique may be a better way for this scenario. this reduces the complexity of the code.
Thanks a lot sTOPs.:)
Christoph Keller 19-Jul-11 8:32am    
you're welcome! :)
How to use the close button in crystal report
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900