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
-
- #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
-
- #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