Updated April 5, 2023
Introduction to LINQ Where
LINQ Where is a LINQ extension method which is used to filter the collection of elements based on the given condition. The condition can be precise as Func delegate type or in the lambda expression. This will be applicable in method syntax as well as in query syntax. In a single query, we can do multiple where extension methods.
Syntax of LINQ Where
Given below is the syntax of Where clause.
public static IEnumerable<TSource> Where<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate);
public static IEnumerable<TSource> Where<TSource>(this IEnumerable<TSource> source, Func<TSource, int, bool> predicate);
These two methods both allow the Func delegate type argument. The first method requires the Func<TSource, bool> as input argument and the second method requires Func<TSource, int, bool> as input parameter here int describes the index value.
Example:
Code:
var _methodSyntax = employeeList.Where(emp => emp.empAge > 25);
var _querySyntax = from s in employeeList
where emp.empAge > 25
select emp.empName;
How Where Works in LINQ?
The main purpose of LINQ where is used to filter elements based on the conditions. It comes under the filtering operator category. It applies in both method and query syntax whereas method syntax requires the lambda expression and query syntax requires only the expression. The LINQ Where is used to limit the number of records from select, update, delete statements.
Given below are few examples of LINQ where code the list of elements in the collection.
1. Sequence of strings with single condition
var _courseName=new List<string>() {"C","C++","DotNet", "Java","Android"};
In Lambda Expression we were getting the result of course names with the condition of the beginning letter start with “C”.
Var result=_courseName.where(c=>c.StartsWith("C"));
In Query Expression, same as above criteria.
Var result=from c in _CourseName
where c.StartsWith("C")
select c;
We can display the result by using foreach to listing the items, the output will be C and C++.
foreach(var items in result)
console.WriteLine(item);
2. Sequence of strings with multiple conditions
var _courseName=new List<string>() {"C","C++","DotNet", "Java","Android"};
In this collection it retrieves the items based on given multiple criteria, it checks the length of the character which is more than 3 characters, and also it checks the beginning letter which should not start with “J”.
In Lambda Expression we were getting the result of course names with the condition of the beginning letter not starts with “J” and the length of the string should be more than 3.
Var result=_courseName.where(c=>c.Length>3 && !c.StartsWith("J"));
In Query Expression, same as above criteria.
Var result=from c in _CourseName
where c.Length >3 && !c.StartsWith("J")
select c;
We can display the result by using foreach to listing the items, the output will be “DotNet”, “Android”.
foreach(var items in result)
console.WriteLine(item);
3. Sequence of objects with single conditions
Employee class to retrieve the records based on single where condition.
public class EmployeeClass
{
public int emp_id { get; set; }
public string emp_name { get; set; }
public int emp_salary { get; set; }
}
List<EmployeeClass> employeeList = new List<EmployeeClass>()
{
new EmployeeClass() { emp _id = 1001, emp _name = "Smith", emp _salary = 30000},
new EmployeeClass() { emp _id = 1002, emp _name = "Sasha", emp _salary = 27000},
new EmployeeClass() { emp _id = 1003, emp _name = "Ricky", emp _salary = 55000},
new EmployeeClass() { emp _id = 1004, emp _name = "Peter", emp _salary = 95000}
};
In Lambda Expression we were getting the result of employeeList with the condition of the employee salary greater than 50000.
Var result= employeeList.where(emp=>emp.emp_salary>50000);
In Query Expression, same as above criteria.
Var result=from emp in employeeList
where emp.emp_salary >50000
select emp;
We can display the result by using foreach to listing the items; the output will be “Ricky”, “Peter”.
foreach(var items in result)
console.WriteLine(item. emp _name);
4. Sequence of numbers with multiple where
In this example, the Employee Class is listed to retrieve the records using multiple where condition applied.
Example:
List<EmployeeClass> employeeList = new List<EmployeeClass>()
{
new EmployeeClass() { emp _id = 1001, emp _name = "Smith", emp _salary = 30000},
new EmployeeClass() { emp _id = 1002, emp _name = "Sasha", emp _salary = 27000},
new EmployeeClass() { emp _id = 1003, emp _name = "Ricky", emp _salary = 42000},
new EmployeeClass() { emp _id = 1004, emp _name = "Peter", emp _salary = 95000}
};
In Lambda Expression we were getting the result of employee names with the condition of the beginning letter starts with “S” and the employee salary must be less than 50000.
Var result= employeeList.where(e=>e. emp _salary <50000).where(e=>e.StartsWith("S"));
In Query Expression, same as above criteria.
Var result=from e in employeeList
where e.emp_salary<50000
where e.emp_name.StartsWith("S")
select e;
We can display the result by using foreach to listing the items, the output will be “Smith”, “Sasha”.
foreach(var items in result)
console.WriteLine(item.emp_name);
Example of LINQ Where
Given below is the example mentioned:
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Console_LINQWhere
{
class ProductClass
{
public int P_ID {get; set;}
public string P_Category { get; set; }
public string P_Name { get; set; }
public int P_Cost { get; set; }
}
class Program
{
static void Main(string[] args)
{
// Creating the product details List
IList<ProductClass> P_List = new List<ProductClass>();
P_List.Add(new ProductClass { P_ID = 1005, P_Category = "Snacks", P_Name = "Biscuits", P_Cost = 20 });
P_List.Add(new ProductClass { P_ID = 1006, P_Category = "Snacks", P_Name = "Dates", P_Cost = 60});
P_List.Add(new ProductClass { P_ID = 1007, P_Category = "Snacks", P_Name = "Honey", P_Cost = 110 });
P_List.Add(new ProductClass { P_ID = 1008, P_Category = "Snacks", P_Name = "Chips", P_Cost = 35 });
P_List.Add(new ProductClass { P_ID = 1009, P_Category = "Stationery", P_Name = "A4 Sheet Bunddle", P_Cost = 100 });
P_List.Add(new ProductClass { P_ID = 1010, P_Category = "Stationery", P_Name = "Pencil Box", P_Cost = 52});
P_List.Add(new ProductClass { P_ID = 1011, P_Category = "Stationery", P_Name = "Ink-Bottle", P_Cost = 45 });
P_List.Add(new ProductClass { P_ID = 1012, P_Category = "Stationery", P_Name = "NoteBooks", P_Cost = 75 });
var result_where = P_List.Where(p=>p.P_Category.StartsWith("S")).Where(p => p.P_Cost > 50);
Console.WriteLine("\nLINQ WHERE");
Console.WriteLine("\n----------");
Console.WriteLine("\nProduct ID\tProduct Name \n");
Console.WriteLine("\n----------\t----------------- \n");
foreach (var res in result_where)
{
Console.WriteLine("\n"+res.P_ID+"\t\t"+res.P_Name);
}
Console.WriteLine("\n----------\t-----------------\n");
Console.ReadKey();
}
}
}
Output:
Conclusion
In this article, we have seen LINQ Where which is used to retrieve a collection of elements based on a given condition. By using the where method we can limit the records easily based on several criteria.
Recommended Articles
This is a guide to LINQ Where. Here we discuss the introduction, how where works in LINQ and examples for better understanding. You may also have a look at the following articles to learn more –