techV
techV

Reputation: 935

Use linq equivalent of sql IN operator

I have following linq statement in which I want to use linq equivalent of SQL IN operator. I have a string variable having values like {1,2}.

    string items = "1,2";
    var objList = from p in db.firsttable 
                  join q in db.secondtable on q.id equals p.someid
                  where items.Contains(p.id)
                  select new 
                  {
                    p.id,
                    p.column1,
                    p.column2,
                    q.column3

                  }

But I am unable to get the output from the above linq statement. Please help me out.

Upvotes: 3

Views: 420

Answers (1)

Taher  Rahgooy
Taher Rahgooy

Reputation: 6696

if p.id is string you should split the items values:

string[] items = "1,2".Split(',');
var objList = from p in db.firsttable 
          join q in db.secondtable on q.id equals p.someid
          where items.Contains(p.id)
          select new 
          {
            p.id,
            p.column1,
            p.column2,
            q.column3

          }

and if p.id is int you should split the items values and then parse them to int:

 int[] items = "1,2".Split(',').Select(x=> int.Parse(x)).ToArray();

Upvotes: 3

Related Questions