LINQ Where Clause Filtering Operator

Linq filtering operators are used to filter the collection or list. Filtering operator specifies the statement that should only take effect when the specified criteria meet. The where clause is optional and used to limit the number of data returned by the linq query.

Linq Where Operator with Method Syntax

Syntax:

collection name.Where(x=>x.StartWith("F"))

Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LinqDemoes
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] state = { "Surat", "Ahmedabad", "Rajkot", "Gandhinagar", "Saurashtra", "Anand" };
            IEnumerable<string> response = state.Where(x => x.StartsWith("A"));
            foreach (var country in response)
            {
                Console.WriteLine(country);
            }
            Console.ReadLine();
        }
    }
}

We are using StartsWith() method for matching the string content. In standard SQL we were using like operator for this. Also others like Contains(), etc. can be used with this and many more.

Output:

Ahmedabad
Anand

Linq Where Operator Query Syntax

Syntax

IEnumerable<string> response = from x in state where x.StartsWith("A") select x;

Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LinqDemoes
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] state = { "Surat", "Ahmedabad", "Rajkot", "Gandhinagar", "Saurashtra", "Anand" };
            IEnumerable<string> response = from x in state
                                         where x.StartsWith("A")
                                            select x;
            foreach (var country in response)
            {
                Console.WriteLine(country);
            }
            Console.ReadLine();
        }
    }
}

Output:

Ahmedabad
Anand

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories