Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Contains(), how to reverse using lambda

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

From this I put together a string variable (p) that contains all the numbers I want to include in the LINQ-statement. Let say if all the checkboxes are checked, i would get a string that is "1234", and if only checkbox 2 and 4 are checked, it would result in "24".

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

Something like this (of course my code doesn't work, therefore I need you 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 kinda need to do is a reversed Contains(), but how?

like image 391
Mikael Edebro Avatar asked Apr 25 '12 13:04

Mikael Edebro


2 Answers

Not clear what the problem is, but this should work:

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

p is string and Contains(string value) expects string as parameter, so you don't need lambda expression.

like image 174
Renatas M. Avatar answered Oct 18 '22 04:10

Renatas M.


Contains() already is a 'reversed 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 simply fill a 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));
like image 1
CodeCaster Avatar answered Oct 18 '22 02:10

CodeCaster