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
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.