LINQ / C#

LINQ Where Filtering Operator

LINQ where operator comes in Filtering operators category. Here is a list of all LINQ Operators.

Where operator filter the list based on some given criteria. Where operator is an extension method which accept a Func delegate as a parameter.

Func accept only a single argument element. An element is passed to argument automatically by LINQ. In the predicate, we’ll give a lambda expression which contains a condition and must return a bool value.

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);

C# Example of LINQ Where Clause in Query Syntax

Below example in C# filter a list of courses based on a condition where Rank is greater than 3.

List<Course> courses = new List<Course>();
courses.Add(new Course {
    ID = 1,
    Subject = "LINQ Tutorials",
    Rank = 5
});

courses.Add(new Course
{
    ID = 2,
    Subject = ".NET Threading Tutorials",
    Rank = 4
});

courses.Add(new Course
{
    ID = 3,
    Subject = "Learn WPF",
    Rank = 3
});

var result = from course in courses
                where course.Rank > 3
                select course;

foreach (var course in result)
{
    Console.WriteLine(course.Subject);
}

Results
--------

LINQ Tutorials
.NET Threading Tutorials

C# Example of LINQ Where Clause in Method Syntax

Below is the example of same above query using Method Syntax. You can learn more about Method Syntax here.

List<Course> courses = new List<Course>();
courses.Add(new Course
{
    ID = 1,
    Subject = "LINQ Tutorials",
    Rank = 5
});

courses.Add(new Course
{
    ID = 2,
    Subject = ".NET Threading Tutorials",
    Rank = 4
});

courses.Add(new Course
{
    ID = 3,
    Subject = "Learn WPF",
    Rank = 3
});

var result = courses.Where(c => c.Rank > 3);

foreach (var course in result)
{
    Console.WriteLine(course.Subject);
}

Results
--------

LINQ Tutorials
.NET Threading Tutorials

LINQ Where Clause with multiple conditions

Sometimes we have to use multiple conditions with where clause. We need to put && operator to separate conditions. Below is the example of multiple conditions.

var result = from course in courses
                where course.Rank > 3 && course.Subject.Contains("Threading")
                select course;

foreach (var course in result)
{
    Console.WriteLine(course.Subject);
}