Find 2nd max salary using linq

前端 未结 6 544
执笔经年
执笔经年 2021-01-02 07:47

I have following sql query for finding 2nd max salary.


Select * From Employee E1 Where
    (2) = (Select Count(Distinct(E2.Salary)) From Employee E2 Where
               


        
6条回答
  •  無奈伤痛
    2021-01-02 08:15

    You can define equally comparer class as bellow:

        public class EqualityComparer : IEqualityComparer
        {
            #region IEqualityComparer Members
            bool IEqualityComparer.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.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.

提交回复
热议问题