Linq and Lamda Expression

Lamda Expression:

(input Parameter) => Method Expression

1) The input parameters are not defined previously and is determined dynamically when the expression is evaluated


LINQ : is ‘Language Integrated Query
Basically, LinQ provides a whole new way to manipulate data, either to/from database, or with XML file or with simple list of dynamic data.

Basic example of Linq Query using employee list. Getting the names of employees having age greater than 24

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

namespace Linq_Lambda_Practice
{

    class Employee
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public static List<Employee> emp;

        //Constructor is declared static since employee object needs to be created only once.
        static Employee()
        {
             emp= new List<Employee>();
            
        }

       // A normal constructor is declared since which will add the employee to the list using "this operator"
        public Employee()
        {
            emp.Add(this);
        }

   
    }

    class Program
    {
        static void Main(string[] args)
        {

            Employee emp1 = new Employee() { Name = "EMP1", Age = 25 };
            Employee emp2 = new Employee() { Name = "EMP2", Age = 27 };
            Employee emp3 = new Employee() { Name = "EMP3", Age = 26 };
            Employee emp4 = new Employee() { Name = "EMP4", Age = 23 };
            Employee emp5 = new Employee() { Name = "EMP5", Age = 24 };
            Employee emp6 = new Employee() { Name = "EMP6", Age = 21 };

            foreach (Employee emp in Employee.emp)
            {
                Console.WriteLine(emp.Name);
            }

            var employee_name = from names in Employee.emp
                        where names.Age > 23
                        select names.Name;

            Console.WriteLine("People with more age group ");

            foreach (string name in employee_name)
            {
                Console.WriteLine(name);
            }

            Console.ReadLine();
        }
    }
}


Comments

Popular posts from this blog

Authentication and Authorization in Web API -Part1

My Gardening Journey 6