0

I'm trying to get results similar to SQL IN clause in terms of LINQ with the help of Contains()

I'm doing the following:

listData.Where(pr => pr.CD.Contains(cd)).Select(pr => pr.dept_cd).Distinct()

This works if cd is only one value, but not working when cd is a comma-separated string.

How can I achieve SELECT * FROM TABLE WHERE COLUMN IN(VALUE1,VALUE2...) in case of LINQ?

Qantas 94 Heavy
  • 15,750
  • 31
  • 68
  • 83
user3085995
  • 433
  • 1
  • 6
  • 19
  • 1
    Do you mean something like `cd.Split(',').Contains(pr.CD)` (although you may want to split into an array on a previous line instead of as part of the Linq expression)? – Joachim Isaksson Feb 04 '14 at 05:44
  • Please check below link [IN clause with LINQ][1] [1]: http://stackoverflow.com/questions/959752/where-in-clause-in-linq – Lajja Thaker Feb 04 '14 at 05:46

2 Answers2

0

use it like as follow

var selected = from u in users
               where new[] { "IT", "Admin", "HR" }.Contains(u.dept_cd)
               select u;

or if you have List of string then you should use it as

List<string> dept= new List<string>(){"HR", "IT"};

var selected = from u in users
               where dept.Contains(u.dept_cd)
               select u;
Usman
  • 3,200
  • 3
  • 28
  • 47
0

It should be reverse. Like below :

listData.Where(pr => cd.Contains(pr.CD).Select(pr => pr.dept_cd)).Distinct();

Not sure of syntax. But this is the approach. Here, cd is the comma separated string or a string array

har07
  • 88,338
  • 12
  • 84
  • 137
Anil Soman
  • 2,443
  • 7
  • 40
  • 64