C# and LINQ – Filter elements from object collection using where clause


This content was proof-read by Grammarly. You can Try Grammary for FREE

Here’s a sample code snippet demonstrating how to filter elements from a list of objects using the where clause using LINQ in C#. This sample gets all the employees who salary is greater than 20000 GBP.

How to Filter Employees List whose salary is greater than 20000 GBP using LINQ in C# ?

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

namespace AbundantcodeCsharpSample
{
    class Program
    {
        static void Main(string[] args)
        {
            List<Employee> employees = new List<Employee>();
            employees.Add(new Employee { Name = "Michael", Age = 55, Salary = 80000 });
            employees.Add(new Employee { Name = "Steve", Age = 23, Salary = 19000 });
            employees.Add(new Employee { Name = "John", Age = 55, Salary = 23000 });
            var output = from m in employees
                         where m.Salary > 20000
                         select m;
            Debug.WriteLine("Employees whose salary is greater than 20000 pounds");
            foreach (var item in output)
                Debug.WriteLine(item.Name);
        }
    }
    class Employee
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public decimal Salary { get; set; }
    }
}

Output

Employees whose salary is greater than 20000 pounds

Michael

John

Newsletter Signup

Subscribe to our weekly newsletter below and never miss the latest product or an exclusive offer.

Newsletter Signup

Subscribe to our weekly newsletter below and never miss the latest product or an exclusive offer.

%d bloggers like this: