Kiran Waghule
Kiran Waghule

Reputation: 71

What is the alternative for IN sql operator in LINQ for string field?

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

Answers (2)

user2051770
user2051770

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

Eric J.
Eric J.

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

Related Questions