Suresh Behera

The Microsoft .Net Junkies

News

Blogroll

Reading

Easy way to write WHERE IN clause in Linq

I found many links to write IN clause in Linq but following is the simplest way achieve this

public IEnumerable<Products> GetProductsByIds(List<int > ids)
{
    from id in Products
    where (x => ids.Contains(x.Id))
    select new {x.Id, x.ProductName};
}

var productids = new List<int> { 33,34,35,36 };

GetProductsByIds(productids);

 

Happy Coding..!

Suresh Behera

Posted: Apr 29 2011, 02:54 PM by Suresh Behera | with 1 comment(s) |
Filed under: ,

Comments

codingslave said:

The above example does not compile. Instead you could do

productids.Where(x => productids.Contains(x.Id));

You don't need to create an extra method and this is simple enough.

# April 29, 2011 4:15 PM