C# - Check a specified employee exists in employees list using LINQ

Learn, how to check a specified employee exists in the list of employees using Linq in C#?
By Nidhi Last updated : April 01, 2023

Here, we will create a list of employees that contains employee details then we use Linq Contains() method to check specified employee record is exist in Employee list or not.

C# program to check a specified employee exists in the list of employees using LINQ

The source code to check a specified employee exists in the list of employees using Linq is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

// C# program to check specified employees exist 
// in the list of employees using Linq.

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

public class Employee {
  int ID;
  string Name;
  int Salary;
  string Department;

  static void Main(string[] args) {
    bool isExist = false;

    List <Employee> employees = new List <Employee> () {
      new Employee {ID = 101, Name = "Amit  ", Salary = 4000, Department = "ABC"},
      new Employee {ID = 102, Name = "Amit  ", Salary = 3000, Department = "XYZ"},
      new Employee {ID = 103, Name = "Salman", Salary = 3000, Department = "ABC"},
      new Employee {ID = 104, Name = "Ram   ", Salary = 2000, Department = "XYZ"},
      new Employee {ID = 105, Name = "Shyam ", Salary = 7000, Department = "ABC"},
      new Employee {ID = 106, Name = "Kishor", Salary = 5000, Department = "XYZ"}
    };

    Employee Emp1 = new Employee() {
      ID = 107, Name = "Amit  ", Salary = 4000, Department = "ABC"
    };

    isExist = employees.AsEnumerable().Contains(Emp1);

    if (isExist == true)
      Console.WriteLine("Emp1 exists in the employees list");
    else
      Console.WriteLine("Emp1 does not exist in the employee's list");
  }
}

Output

Emp1 does not exist in the employee's list
Press any key to continue . . .

Explanation

In the above program, we created a class Employee that contains data members ID, Name, Salary, and Department and Main() method. In the Main() method we created a list of employees, and we also created an object of Employee class that contains employee records.

isExist = employees.AsEnumerable().Contains(Emp1);

The Contain() method will return false because employee Emp1 does not exist in the List of employees. Then "Emp1 does not exist in the employees' list" message will print on the console screen.

C# LINQ Programs »




Comments and Discussions!

Load comments ↻





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