I have user-interface where user can select grid column (like age) and operator (lesser than, equals or greater than) for that column.
Grid data is then filtered according to the selection.
I have a following classes that are deserialized from the JSON that is coming from the client.
/// <summary>
/// Filter for reducing grid results
/// </summary>
public class Filter
{
/// <summary>
/// Name of the column
/// </summary>
public string name;
public string value;
public int @operator { private get; set; }
public Operator Operator()
{
return (Operator) @operator;
}
}
public enum Operator
{
None = -1,
LesserThan = 0,
Equals = 1,
GreaterThan = 2
}
Due to the nature dynamically adding new columns for filtering I would like to create generic solution for accessing the data.
I would like avoid having huge amount if/switch statements like
switch(columnName)
{
case "age":
{
if(operator == Operator.LesserThan)
{
query = entities.Where(o => o.Age < age);
}
else if (operator == Operator.GreaterThan)
{
query = entities.Where(o => o.Age > age);
}
etc.
break;
}
etc.
}
Any ideas how to create more generic solution for the problem?
Update
It seems that there many ways to accomplish cleaner solution than one billion if statements. Now I just need to compare different solutions.
You could use Dynamic LINQ to create the query dynamically
Edit:
An example for Dynamic LINQ query would look like this, assuming that the column names in the grid are the same as the field names in the entity: