Linq Where Clause

Linq Where Clause

Linq Where Clause. Linq Where Clause is used to filter rows based on criteria. Here we will see how to use where clause in Linq query expressions. We will query Products table and get results containing those products whose category ID is 5. We are using North Wind database.

C# Linq Where Clause.

// var products is equivalent to IEnumerable<Products>

var products = from productList in Products
where productList.CategoryID == 5
select productList;

Equivalent SQL statement of above Linq where clause example.

DECLARE @p0 Int SET @p0 = 5
-- EndRegion
SELECT [t0].[ProductID], [t0].[ProductName], [t0].[SupplierID], [t0].[CategoryID], [t0].[QuantityPerUnit], [t0].[UnitPrice], [t0].[UnitsInStock], [t0].[UnitsOnOrder], [t0].[ReorderLevel], [t0].[Discontinued]
FROM [Products] AS [t0]
WHERE [t0].[CategoryID] = @p0

Linq Extension Where Method Example.

Products.Where (productList => (productList.CategoryID == (Int32?)5))

Linq Select Columns example.

The above example uses where clause to filter Products by Category ID. It gives all columns in Product table or List. Lets see how to select columns into products list.

// var products is equivalent to IEnumerable<Products>

var products = from productList in Products
where productList.CategoryID == 5
select new { ProductName = productList.ProductName, Quantity = productList.QuantityPerUnit  };

Output

Linq select columns and where clause to filter the rows.

The output list of products contain only Product Name and Quantity columns from table.

Equivalent SQL statement of Linq Select columns.

-- Region Parameters
DECLARE @p0 Int SET @p0 = 5
-- EndRegion
SELECT [t0].[ProductName], [t0].[QuantityPerUnit] AS [Quantity]
FROM [Products] AS [t0]
WHERE [t0].[CategoryID] = @p0

Tags:

Linq Where ClauseLinq Split String To ListLearn Linq Step By StepLinq Inner JoinLinq Get Duplicate Count Of Words From StringLinq Distinct ListHow to select multiple columns in Linq- C#.net VB.net codeLinq Union and intersect ExampleC# ArrayList Search using Linq Extension OfType MethodLinq ToDictionary ExtensionLinq to Sql

Author

My name is Satalaj, but people call me Sat. Here is my homepage: . I live in Pune, PN and work as a Software Engineer. I'm former MVP in ASP.net year 2010.
Disclaimer: Views or opinion expressed here are my personal research and it has nothing to do with my employer. You are free to use the code, ideas/hints in your projects. However, you should not copy and paste my original content to other web sites. Feel free to copy or extend the code.
If you want to fight with me, this website is not for you.
 

I'm Satalaj.