LINQ, where in (Value1, Value2, Value3.) equivalent Statement.


This Code Segment Help you to write Where in (x1, x2 ) equivalent statement in LINQ. The "IN" clause is built in linq via the .Contains() method

While Working, I have come across scenario to write Linq equivalent for following query.


SELECT ID,Name, ContactTitle, Address, City, Region, PostalCode,
Country, Phone FROM Author WHERE Country IN ('UK', 'USA', 'Australia')


Please see the Equivalent statement in LINQ below...

Query syntax




 string[] countries = new string[] { "UK", "USA", "Australia" };  

var Author = from c in context.Author s
where countries.Contains(c.Country)
select c;


Lambda expression



string[] countries = new string[] { "UK", "USA", "Australia" };  

var Author = Author.Where(c => countries.Contains(c.Country));


Comments

Author: Subhashini Janakiraman30 Dec 2010 Member Level: Silver   Points : 0

I have a query.What does context.Author s refer to?

Author: Subhashini Janakiraman30 Dec 2010 Member Level: Silver   Points : 1

I have another way of giving the above code.Hope this also works.
var auth=db.Authors.
SelectMany(n=>countries.Where
(p=> n equals p.Country));
foreach(var countrys in auth)
{
Console.WriteLine(countrys.ToString());
}

Author: Siva Prasad22 Jul 2012 Member Level: Gold   Points : 0

While executing your code I'm getting below errors.
Error 1: The name 'context' does not exist in the current context.

Error 2: Cannot use local variable 'Author' before it is declared.



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: