Contains () how to cancel the use of lambda

I have these 4 checkboxes that make up the string variables saljes, kopes, bytes, erbjudes. When they are checked, they get the value "on".

From this, I compiled a string variable (p) that contains all the numbers that I want to include in the LINQ statement. Say, if all the checkboxes are checked, I would get a line that is "1234", and if only checkboxes 2 and 4 are checked, this will lead to "24".

In my database, I have a field called "Type" that is of type int. I want to tell the database to include all rows that have a Type value, which can be found in row p.

Something like this (of course, my code is not working, so I need guys):

var searchResult = from s in db.Ads select s; string p = "1"; if (saljes != "on") p = p.Replace("1", ""); if (kopes == "on") p += "2"; if (bytes == "on") p += "3"; if (erbjudes == "on") p += "4"; searchResult = searchResult.Where(s => p.Contains(s => s.Type.ToString()); 

What I need to do is the opposite of Contains (), but how?

+6
source share
3 answers

Contains() already has a "reverse IN", as described here :

 int[] productList = new int[] { 1, 2, 3, 4 }; var myProducts = from p in db.Products where productList.Contains(p.ProductID) select p; 

So just fill out the list:

 var list = new List<int>(); if (saljes == "on") list.Add(1); if (kopes == "on") list.Add(2); if (bytes == "on") list.Add(3); if (erbjudes == "on") list.Add(4); var searchResult = db.Ads.Where(s => list.Contains(s.Type)); 
+1
source

It's not clear what the problem is, but this should work:

 searchResult = searchResult.Where(s => p.Contains(s.Type.ToString()); 

p is a string and Contains (string value) expects a string as a parameter, so you do not need a lambda expression.

+3
source

Will this expression do it?

 s => s.Type.ToString().ToCharArray().Except(p.ToCharArray()).Count() == 0 

eg. if s.Type is 24 and p is "234" , then s.Type included in the string. If we convert int to char -array, we get

 {'2', '4'} 

String converted to char -array,

 {'2', '3', '4'} 

This means that the digits int all included in the string . Thus, the digits int , in addition to the digits string , give an empty set, which we test using Count() == 0 .

 {'2', '4'}.Except({'2', '3', '4'}) ==> { } 

Instead of creating a string I would create a List<char>

 var p = new List<char>(); if (saljes == "on") p.Add('1'); if (kopes == "on") p.Add('2'); if (bytes == "on") p.Add('3'); if (erbjudes == "on") p.Add('4'); 

Then the expression becomes

 s => s.Type.ToString().ToCharArray().Except(p).Count() == 0 

However, keep in mind that this cannot be converted to the corresponding SQL-where clause. Therefore, the entire table will need to be scanned.

+1
source

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


All Articles