C# - Print the employees whose id is greater than 101 using LINQ

Learn, how to print the employees whose id is greater than 101 using LINQ in C#? By Nidhi Last updated : April 01, 2023

Printing employee's information (where, id > 10)

Here, we will create an Employee class that contains ID and Name and we created List collection for employees and search only those employees whose ID is greater than 101 using LINQ and print them on the console screen.

C# program to print the employees whose id is greater than 101 using LINQ

The source code to print employee details using LINQ in C# is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

//Program to print the employees whose 
//id is greater than 101 using LINQ.

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

public class Employee {
  int ID;
  string Name;

  public override string ToString() {
    return ID + " " + Name;
  }

  static void Main(string[] args) {
    List < Employee > employees = new List < Employee > () {
      new Employee {
        ID = 101, Name = "Amit"
      },
      new Employee {
        ID = 102, Name = "Gautam"
      },
      new Employee {
        ID = 103, Name = "Salman"
      },
      new Employee {
        ID = 104, Name = "Ram"
      },
    };

    IEnumerable < Employee > Query =
      from emp in employees
    where emp.ID > 101
    select emp;

    Console.WriteLine("ID  Name");
    Console.WriteLine("==============");
    foreach(Employee s in Query) {
      Console.WriteLine(s.ToString());
    }
    Console.WriteLine("==============");
  }
}

Output

ID  Name
==============
102 Gautam
103 Salman
104 Ram
==============
Press any key to continue . . .

Explanation

In the above program, we created an Employee class that contains two data members ID and Name. Here we override the ToString() method to return ID and name from the ToString() method.  The Employee class also one more method is known as Main().

List<Employee> employees = new List<Employee>()
{
        new Employee {ID=101,   Name="Amit"    },
        new Employee {ID=102,   Name="Gautam"  },
        new Employee {ID=103,   Name="Salman"  },
        new Employee {ID=104,   Name="Ram"     },
};

In the Main() method, we created List collection for Employees, It contains information of 4  employees.

IEnumerable<Employee> Query =
    from emp in employees
    where emp.ID > 101
    select emp;

In the above code, we created a query to get a list of employees whose ID is greater than 101. Then we printed the Employee detail using the "foreach" loop on the console screen.

C# LINQ Programs »




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.