Finding the maximum value in a sequence.
Think that we have a student class as following
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
public class Student { public int Age; public string Name; public int Grade; public Student(int age,string name, int grade ) { this.Age = age; this.Name = name; this.Grade = grade; } } |
For tutorial, list sequences like this
1 2 3 4 5 6 7 |
List<Student> students = new List<Student>(); students.Add(new Student(12, "Mark", 5)); students.Add(new Student(11, "Nicole", 4)); students.Add(new Student(13, "Nicke", 6)); students.Add(new Student(10, "Grace", 3)); |
And I want to find oldest stutent’s age from the sutents list, here is the Linq Code
1 2 3 |
int maxAge = students.Max(s => s.Age); |
If you want to find oldest student’s name from the list using LINQ
1 2 3 4 5 6 7 8 |
//stList sorted by Age Student st = (from element in students orderby element.Age descending select element).First(); Console.WriteLine(st.Name); |