Want to become a Vibe Coder? Join Vibe Coding Training here
x
C# Corner
Tech
News
Videos
Forums
Jobs
Books
Events
More
Interviews
Live
Learn
Training
Career
Members
Blogs
Challenges
Certification
Contribute
Article
Blog
Video
Ebook
Interview Question
Collapse
Feed
Dashboard
Wallet
Learn
Achievements
Network
Refer
Rewards
SharpGPT
Premium
Contribute
Article
Blog
Video
Ebook
Interview Question
Register
Login
How To Use Multiple Where Condition In LINQ
WhatsApp
Gnanavel Sekar
7y
525
k
0
9
25
Blog
MultipleWhereinLinq.zip
In some situations we are in a position to check two conditions in our logic. So now shall we see how to use the multiple where clause in a linq and lambda query. For that I have created a class and list with dummy values as shown below
public
class
Farmers {
public
int
ID {
get;
set;
}
public
string Name {
get;
set;
}
public
string Location {
get;
set;
}
public
double
Income {
get;
set;
}
}
List < Farmers > farmerList =
new
List < Farmers > {
new
Farmers {
ID = 1, Name =
"Sekar L"
, Location =
"Krishnagiri"
, Income = 21000
},
new
Farmers {
ID = 2, Name =
"Mohan S"
, Location =
"Krishnagiri"
, Income = 40000
},
new
Farmers {
ID = 3, Name =
"Sathis S"
, Location =
"Krishnagiri"
, Income = 18000
},
new
Farmers {
ID = 4, Name =
"Subash S"
, Location =
"Ooty"
, Income = 25000
},
new
Farmers {
ID = 5, Name =
"Robert B"
, Location =
"Banglore"
, Income = 28000
},
};
foreach(
var
farmer
in
farmerList) {
Console.WriteLine(
"ID : "
+ farmer.ID +
" Name : "
+ farmer.Name +
"Income : "
+ farmer.Income);
}
Result
The above image represents the collection values, now we're going to filter the income between 25,000 and 40,000 using multiple where conditions, we see this in both the linq and lambda query
Linq Query
//Linq
#region Linq Deffered Query
var
result = from farmer
in
farmerList
where farmer.Income > 25000
where farmer.Income < 40000
select farmer;
#endregion
Console.WriteLine(
"Linq Query"
);
#region Linq Immediate Query Result
foreach (
var
farmer
in
result)
{
Console.WriteLine(
"ID : "
+ farmer.ID +
" Name : "
+ farmer.Name +
"Income : "
+ farmer.Income);
}
#endregion
Result
Lambda Query
//Lambda
#region Lambda deffered query
var
result1 = farmerList.Where(a => a.Income > 25000).Where(a => a.Income < 40000);#
endregion
Console.WriteLine(
"Lambda Query"
);
#region Lambda Immediate Query Result
foreach(
var
farmer
in
result1) {
Console.WriteLine(
"ID : "
+ farmer.ID +
" Name : "
+ farmer.Name +
"Income : "
+ farmer.Income);
}
#endregion
Result
Detailed description
We have specified two where conditions in both linq and lambda queries. The first where clause checks for the income that is greater than 25,000 and the second where clause looks for the income that is less than 45,000. We can see there is just one income between 25000 and 40000. So we should be getting this as output from both queries.
I hope it's helpful
LINQ
Multiple where
lambda
People also reading
Membership not found