C# LINQ In Clause

In Clause in LINQ can seem a bit tricky when you first write one. These two Northwind Traders SQL examples of a LINQ In Clause includes using a list as the in clause, and using a query as the in clause.

//--------------------------------------------------------------------------------    
//1. In Clausing using a LIST
//--------------------------------------------------------------------------------
List<decimal> OrderList = new List<decimal>();    
OrderList.Add(10248);
OrderList.Add(10250);
var OrderListArr = OrderList.ToArray();

var CustOrders = from o in Orders
                 where OrderListArr.Contains(o.OrderID)
                 select o;
    
CustOrders.Dump();

//--------------------------------------------------------------------------------
//2. In Clause using a LINQ statement. Get Customer Orders from Brazil customers
//--------------------------------------------------------------------------------
var BrazilOrders = from o in Orders
                   where (from c in Customers
                         where c.Country.Contains("Brazil")
                         select c.CustomerID).Contains(o.CustomerID)
                   select o;
BrazilOrders.Dump();           

Screen Shot from LINQPad for the two queries above.

LINQ - Sample Queries - Source/App

Very cool sample code and app on MSDN or download the source below.

Run the project, and select the type of LINQ sample that you want to examine. Examine the options, and run each query that interests you. The output from the query and the source code is displayed on the interface of the application.

LINQ-Sample-Queries.zip (2.5MB)