Topic
Finding the Second Highest or nth highest using Linq
Scenario
Finding the Second Highest or nth highest using Linq
Scenario
- List of Students. Each having name,Salary etc
- Find the second highest or nth highest salary
Code
using System;
using System.Collections.Generic;
using System.Linq;
namespace XML
{
class Program
{
public class student
{
public int id { get; set; }
public string name { get; set; }
public int classId { get; set; }
public int Salary { get; set; }
public List<student> getStudents()
{
List<student> obj = new List<student>();
obj.Add(new student { id = 101, name = "abc1", classId = 1, Salary = 100 });
obj.Add(new student { id = 102, name = "abc2", classId = 1, Salary = 200 });
obj.Add(new student { id = 103, name = "abc3", classId = 2, Salary = 300 });
obj.Add(new student { id = 104, name = "abc4", classId = 2, Salary = 800 });
obj.Add(new student { id = 105, name = "abc5", classId = 2, Salary = 900 });
obj.Add(new student { id = 106, name = "abc6", classId = 3, Salary = 250 });
obj.Add(new student { id = 107, name = "abc7", classId = 3, Salary = 260 });
obj.Add(new student { id = 108, name = "abc8", classId = 3, Salary = 290 });
return obj;
}
}
static void Main(string[] args)
{
student s = new student();
var students = s.getStudents().ToList();
var firsthighest = students.OrderByDescending(x => x.Salary).Select(x => x.Salary).First();
var secondhighest = students.OrderByDescending(x => x.Salary).Where(x => x.Salary != firsthighest).Select(x => x.Salary).First();
var secondhighest1 = students.OrderByDescending(x => x.Salary).Skip(2).Select(x => x.Salary).First();
var secondhighest2 = students.Where(x => x.Salary != (students.Max(x1 => x1.Salary))).Select(x => x.Salary).Max();
Console.WriteLine(secondhighest1);
Console.WriteLine(secondhighest2);
Console.ReadLine();
}
}
}
Output
No comments:
Post a Comment