How can I find the second maximum number in a list of values using Linq
and C#
?
For example I have this list:
List<double> ListOfNums = new List<double> {1, 5, 7, -1, 4, 8};
Is there a method I can get the second maximum value in the list which is 7?
var secondMax = ListOfNums.OrderByDescending(r => r).Skip(1).FirstOrDefault();
要么
var secondMax = ListOfNums.OrderByDescending(r=> r).Take(2).LastOrDefault();
just convert it to an array and take the second element
List<double> ListOfNums = new List<double> { 1, 5, 7, -1, 4, 8 };
var sndmax = ListOfNums.OrderByDescending(x => x).ToArray()[1];
Here is another way using List<T>.Sort
method:
ListOfNums.Sort();
var max = ListOfNums[1];
For a bit more complicated objects a solution like below could be used. I post just for someone may need have an idea. For example we want to find the 3. Maximum grade point achieved by the students from the list of students.
This is the basic class for create a sample list for us :
public class Students
{
public string StudentName { get; set; }
public int GradePoint { get; set; }
public int StudentId { get; set; }
public List<Students> GetStudentRecords()
{
List<Students> stulist = new List<Students>();
stulist.Add(new Students { StudentId = 1, StudentName = " Joseph ", GradePoint = 800 });
stulist.Add(new Students { StudentId = 2, StudentName = "Alex", GradePoint = 458 });
stulist.Add(new Students { StudentId = 3, StudentName = "Harris", GradePoint = 900 });
stulist.Add(new Students { StudentId = 4, StudentName = "Taylor", GradePoint = 900 });
stulist.Add(new Students { StudentId = 5, StudentName = "Smith", GradePoint = 458 });
stulist.Add(new Students { StudentId = 6, StudentName = "Natasa", GradePoint = 700 });
stulist.Add(new Students { StudentId = 7, StudentName = "David", GradePoint = 750 });
stulist.Add(new Students { StudentId = 8, StudentName = "Harry", GradePoint = 700 });
stulist.Add(new Students { StudentId = 9, StudentName = "Nicolash", GradePoint = 597 });
stulist.Add(new Students { StudentId = 10, StudentName = "Jenny", GradePoint = 750 });
return stulist;
}
}
We call our list and write the output:
class Program
{
static void Main(string[] args)
{
var students = new Students();
students.GetStudentRecords()
.GroupBy(grp => grp.GradePoint)
.OrderByDescending(x => x.Key).Skip(2)
.Take(1)
.SelectMany(s => s)
.ToList()
.ForEach(p =>
Console.WriteLine($"Id : {p.StudentId}, Name : {p.StudentName}, achieved Grade Point : {p.GradePoint} "));
}
}
And this is the output :
Id : 7, Name : David, achieved Grade Point : 750
Id : 10, Name : Jenny, achieved Grade Point : 750
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.