Filtering data in LINQ with the help of where clause
- by vik20000in
LINQ has bought with itself a
super power of querying Objects, Database, XML, SharePoint and nearly any other
data structure. The power of LINQ lies in the fact that it is managed code that
lets you write SQL type code to fetch data.
Whenever working with data we
always need a way to filter out the data based on different condition. In this
post we will look at some of the different ways in which we can filter data in
LINQ with the help of where clause.
Simple Filter for an
array.
Let’s say we have an array of
number and we want to filter out data based on some condition. Below is an
example
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
var lowNums =
from num
in numbers
where num
< 5
select
num;
Filter based on one of the
property in the class.
With the help of LINQ we can
also filer out data from a list based on value of some property.
var soldOutProducts =
from prod
in products
where
prod.UnitsInStock == 0
select prod;
Filter based on Multiple of
the property in the class.
var expensiveInStockProducts =
from prod in
products
where
prod.UnitsInStock > 0 && prod.UnitPrice > 3.00M
select prod;
Filter based on the index of the
Item in the list.In the below example we can see that we are able to filter
data based on the index of the item in the list.
string[] digits = { "zero",
"one", "two", "three", "four", "five", "six"};
var shortDigits =
digits.Where((digit, index) => digit.Length < index);
There are many other way in
which we can filter out data in LINQ. In the above post I have tried and shown
few ways using the LINQ.
Vikram