LINQ Query - Second Highest Salary


Here are some common LINQ queries related to find second highest salary and count each character from string in LINQ.

1. Find Second Highest Salary


            // Sample data
            var employees = new List<Employee>
            {
                new Employee { EmployeeId = 1, FirstName = "Rohatash", LastName = "Doe", Salary = 5000, DepartmentId = 1 },
                new Employee { EmployeeId = 2, FirstName = "Ram", LastName = "Smith", Salary = 7000, DepartmentId = 2 },
                new Employee { EmployeeId = 3, FirstName = "Mohit", LastName = "Gates", Salary = 5000, DepartmentId = 2 },
                new Employee { EmployeeId = 4, FirstName = "Saurav", LastName = "Musk", Salary = 6000, DepartmentId = 3 },
                new Employee { EmployeeId = 1, FirstName = "Jeet", LastName = "Doe", Salary = 5000, DepartmentId = 1 }
            };


            // Find second highest salary using Lamda Expression
            var secondHighestSalary1 = employees.OrderByDescending(x => x.Salary).Skip(1).First();

            Console.WriteLine("Second Highest Salary: " + secondHighestSalary1.Salary);  // Output - 6000


            // Find second highest salary
            var secondHighestSalary = (from employee in employees
                                       orderby employee.Salary descending
                                       select employee.Salary)
                                       .Distinct()
                                       .Skip(1)
                                       .FirstOrDefault();

            Console.WriteLine("Second Highest Salary: " + secondHighestSalary);  // Output - 6000

1. Count Each word from String

Example - String name="Rohatash";

 //Count Each Word from Name

String input = "Rohatash";

var wordCounts = input.GroupBy(word => word).Select(group => new { Word = group.Key, Count = group.Count() }).ToList();
 foreach (var wordCount in wordCounts)
 {
     Console.WriteLine($"Word: {wordCount.Word}, Count: {wordCount.Count}");
 }
 
 //Output    
Word: R, Count: 1
Word: o, Count: 1
Word: h, Count: 2
Word: a, Count: 2
Word: t, Count: 1
Word: s, Count: 1
 
 

Prev Next