C# LINQ Filtering Operator

Updated on     Kisan Patel

Filtering, refers to the operation of filtering the result set so that it contains only these elements that satisfy a specific condition. The where clause is used as the filtering operator in LINQ.

Imagine that you need to list the cities that name start with ‘a’. For this purpose you can use Where operator, which is also called a restriction operator because it restricts a set of items.

For Example,

string[] names = { "Kisan", "Ravi", "Ujas", "Karan", "Ketul"};
IEnumerable<string> query = from n in names
                                    where n.StartsWith("K")
                                    select n;

…would translate into…

IEnumerable<string> query = names.Where( name => name.StartsWith("K"));

Let’s take complete example to understand how to work with where operator.

using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] names = { "Kisan", "Ravi", "Ujas", "Karan", "Ketul"};

            IEnumerable query1 = names.Where( name => name.StartsWith("K"));

            Console.WriteLine("Name Starts with 'K' are : ");

            foreach (string name in query1)
                Console.WriteLine(name);

            Console.WriteLine("Name Ends with 'n' are : ");

            IEnumerable query2 = from n in names
                                         where n.EndsWith("n")
                                         select n;

            foreach (string name in query2)
                Console.WriteLine(name);
        }
    }
}

the output of the above C# program…

linq-where-methods-demo

Now, Let’s take more examples…

NorthwindEntities _db = new NorthwindEntities();

var customers = _db.Customers.
                      Where(x => (x.Country == "USA") && (x.CompanyName.StartsWith("T")));
            
foreach(var customer in customers){
      Console.WriteLine(customer.ContactTitle + " - " + customer.Country);
}

the above code will produce below output…

linq-where-operator-example


C# LINQ

Leave a Reply