tags:

views:

46

answers:

3

I'm new to Linq to Sql and am trying to do the following in C#.

I have a table that's a key/value store (that also has an fk to a user). I want to do a search off the key names and values as an or. On the front end, I allow them to add "filters" that are key names, then they can search for a value. So they can search N items, where N is the number of filters.

In plain sql, where N=3, it'd look like the following. datakey and datavalue are columns in the table (varchar(255)).

SELECT * from table
 where (datakey='option1' and datavalue='value1')
    or (datakey='option2' and datavalue='value2')
    or (datakey='option3' and datavalue='value3')
A: 

Use C#'s equivalent operators, && and ||:

from t in context.table
where (t.datakey == "option1" && datavalue == "value1")
   || (t.datakey == "option2" && datavalue == "value2")
   || (t.datakey == "option3" && datavalue == "value3")
select t
Marcelo Cantos
um, wont that query reduce the result set rather than expanding it? i think you should be using union there
jasper
Marcelo Cantos
i think you were on the right track with your last answer, do the loop through all the expressions, and use union to add all the results together, and filter for duplicates
jasper
@jasper: Yes, that option came up the last time, too. The problem I had with it is that it doesn't produce the same SQL. It is, of course, a perfectly valid answer (pending performance tests).
Marcelo Cantos
Thanks, but N is variable based on the responses from the user, so my issue was I wasn't sure how to build it in a loop or such. I'm using these now in other places no problem.
Ian
+2  A: 

Theres a technology called DynamicQuery which would allow you to build up LINQ expressions via a string, which you may find helpful

jasper
+2  A: 

Yes, as jasper said you can use the Dynamic LINQ Query Library to accomplish what you want.

Here is a quick and dirty example (note: I have not tested this exact code):

List<string> options = new List<string>();
List<string> values = new List<string>();

options.Add("option1");
values.Add("value1");
options.Add("option2");
values.Add("value2");

StringBuilder queryString = new StringBuilder();

for (int i = 0; i < options.Count; i++)
{
    if (queryString.Length > 0)
        queryString.Append(" Or ");

    queryString.Append(string.Format("(datakey = \"{0}\" And dataValue = \"{1}\")", options[i], values[i]));
}

var query = context.YourTable.Where(queryString.ToString());
shaunmartin
Thank you. I gave credit to Jasper, but the sample was a huge help. I was trying this right before I left work Friday, but ran into some issues.
Ian