Linq to sql / C # - several where search for key / value pairs

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

I have a table in which the key / value is stored (which also has fk for the user). I want to search with key names and values ​​like or. At the front end, I let them add “filters”, which are key names, then they can look up the value. Thus, they can search for N elements, where N is the number of filters.

In plain sql, where N = 3, it will look like this. datakey and datavalue are columns in a table (varchar (255)).

SELECT * from table
 where (datakey='option1' and datavalue='value1')
    or (datakey='option2' and datavalue='value2')
    or (datakey='option3' and datavalue='value3')
+3
source share
3 answers

Theres - DynamicQuery, LINQ ,

+1

, jasper , Dynamic LINQ Query , , .

(:  ):

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());
+1

Use equivalent C # 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
0
source

Source: https://habr.com/ru/post/1772255/


All Articles