using System;
using System.Collections.Generic;
using System.Linq;
public class Employee
{
public string Name { get; set; }
public int Salary { get; set; }
}
public class Program
{
public static void Main(string[] args)
{
List<Employee> employees = new List<Employee>
{
new Employee { Name = "Alice", Salary = 80000 },
new Employee { Name = "Bob", Salary = 60000 },
new Employee { Name = "Charlie", Salary = 80000 },
new Employee { Name = "David", Salary = 70000 },
new Employee { Name = "Eve", Salary = 80000 },
new Employee { Name = "Frank", Salary = 70000 },
new Employee { Name = "Grace", Salary = 60000 },
new Employee {Name = "Henry", Salary = 70000}
};
// Get employees with the highest salary
var highestSalary = employees.Max(e => e.Salary);
var highestSalaryEmployees = employees.Where(e => e.Salary == highestSalary).ToList();
Console.WriteLine("Employees with Highest Salary:");
foreach (var employee in highestSalaryEmployees)
{
Console.WriteLine($"Salary: {employee.Salary}, Name: {employee.Name}");
}
// Get employees with the second highest salary
var secondHighestSalary = employees
.OrderByDescending(e => e.Salary)
.Skip(1)
.FirstOrDefault()?.Salary; // Null-conditional operator to handle empty list
if (secondHighestSalary.HasValue)
{
var secondHighestSalaryEmployees = employees
.Where(e => e.Salary == secondHighestSalary)
.ToList();
Console.WriteLine("\nEmployees with Second Highest Salary:");
foreach (var employee in secondHighestSalaryEmployees)
{
Console.WriteLine($"Salary: {employee.Salary}, Name: {employee.Name}");
}
}
else
{
Console.WriteLine("\nThere is no second highest salary.");
}
}
}
- Handles multiple employees with the same highest or second highest salary.
- Uses more efficient LINQ methods for finding the maximum salary.
Leave a Reply