C# and Lambda – Filter elements from object collection with Logical Operators

Published on November 18, 2016 by abundantcode

Filed under C#

Last modified November 18, 2016

Print this page

rate 1 star rate 2 star rate 3 star rate 4 star rate 5 star
Your rating: none, Average: 0 (0 votes)

This article have been viewed 662 times

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

How to Filter Employees List whose salary is greater than 20000 GBP and age is greater than 22 using Lambda 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 = 21, Salary = 19000 });
            employees.Add(new Employee { Name = "John", Age = 55, Salary = 23000 });
            // Lambda expression demonstrating the usage of Logical operators in the Where clause.
            var output = employees.Where(a => a.Salary > 20000 && a.Age > 22);
            Debug.WriteLine("Employees whose salary is greater than 20000 pounds and age > 22");
            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 and age > 22

Michael

John

If you enjoyed this post, please consider leaving a comment or subscribing to the RSS feed to have future articles delivered to your feed reader.

Leave a Comment


x

You might be Interested in these Posts

VB.NET and Lambda – Filter elements from object collection with Logical Operators

Here’s a sample code snippet demonstrating how to filter elements from a list of objects using the w...

C# and LINQ – Filter elements from object collection with Logical Operators

Here’s a sample code snippet demonstrating how to filter elements from a list of objects using the w...

VB.NET and Lambda – Filter elements from object collection using where clause

Here’s a sample code snippet demonstrating how to filter elements from a list of objects using the w...