Find 2nd max salary using linq

You can define equally comparer class as bellow:

    public class EqualityComparer : IEqualityComparer<Employee >
    {
        #region IEqualityComparer<Employee> Members
        bool IEqualityComparer<Employee>.Equals(Employee x, Employee y)
        {
            // Check whether the compared objects reference the same data.
            if (Object.ReferenceEquals(x, y))
                return true;

            // Check whether any of the compared objects is null.
            if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null))
                return false;

            return x.Salary == y.Salary;
        }

        int IEqualityComparer<Employee>.GetHashCode(Employee obj)
        {
            return obj.Salary.GetHashCode();
        }
        #endregion
    }

and use it as bellow:

    var outval = lst.OrderByDescending(p => p.Id)
                  .Distinct(new EqualityComparer()).Skip(1).First();

or do it without equally comparer (in two line):

        var lst2 = lst.OrderByDescending(p => p.Id).Skip(1);
        var result = lst2.SkipWhile(p => p.Salary == lst2.First().Salary).First();

Edit: As Ani said to work with sql should do : var lst = myDataContext.Employees.AsEnumerable(); but if is for commercial software it's better to use TSQL or find another linq way.


I think what you're asking is to find the employee with the second-highest salary?

If so, that would be something like

var employee = Employees
    .OrderByDescending(e => e.Salary)
    .Skip(1)
    .First();

If multiple employees may have equal salary and you wish to return an IEnumerable of all the employees with the second-highest salary you could do:

var employees = Employees
    .GroupBy(e => e.Salary)
    .OrderByDescending(g => g.Key)
    .Skip(1)
    .First();

(kudos to @diceguyd30 for suggesting this latter enhancement)


List<Employee> employees = new List<Employee>()
{
    new Employee { Id = 1, UserName = "Anil" , Salary = 5000},
    new Employee { Id = 2, UserName = "Sunil" , Salary = 6000},
    new Employee { Id = 3, UserName = "Lokesh" , Salary = 5500},
    new Employee { Id = 4, UserName = "Vinay" , Salary = 7000}
};

var emp = employees.OrderByDescending(x => x.Salary).Skip(1).FirstOrDefault();

Tags:

C#

Linq