Reputation: 71
Please find the example below which I am trying to achieve.
List<string> list = new List<string>() { "Test", "Test1", "Test2","Test","Test1" };
SQL = select * from table_name
where column_name IN ("Test","Test1");<br/>
output = { "Test","Test1","Test","Test1"}
LINQ= from x in list where list.Contains("Test","Test1") select x
output = { "Test", "Test1", "Test2","Test","Test1" }
Contains Does not do an exact match.
How can we get the same output as SQL IN operator with string list in LINQ?
Thanks
Upvotes: 0
Views: 182
Reputation: 764
A similar approach to Eric's answer but using join:
var list = new List<string>() { "Test", "Test1", "Test2","Test","Test1" };
var match = new HashSet<string>() { "Test", "Test1" };
var results = from x in list
join y in match on x equals y
select x;
Upvotes: 0
Reputation: 150108
You're using Contains incorrectly (and indeed, your example code doesn't compile). Instead, declare a set that you wish to match against and use Contains on that set, like this:
List<string> list = new List<string>() { "Test", "Test1", "Test2","Test","Test1" };
var match = new HashSet<string>() { "Test", "Test1" };
var result = from x in list where match.Contains(x) select x;
Result:
Test
Test1
Test
Test1
Upvotes: 1