Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.Linq;
- namespace ExamPreparation
- {
- class Program
- {
- static void Main()
- {
- List<Student> oldStudents = new List<Student> { new Student(44, "Ivan Petrov"), new Student(34, "Milen Andonov"), new Student(55, "Dancho Bogdanov"), new Student(34, "Strahil Pavlov") };
- IEnumerable<GroupedStudents> groupedStudentsByAge = oldStudents
- .GroupBy(s => s.Age)
- .OrderByDescending(g => g.Key)
- .Select(g => new GroupedStudents
- {
- Age = g.Key,
- Count = g.Count(),
- Students = g
- });
- PrintGroupedStudent(groupedStudentsByAge);
- }
- public static void PrintGroupedStudent(IEnumerable<GroupedStudents> groupedStudents )
- {
- foreach (var item in groupedStudents)
- {
- Console.WriteLine("There are {0} students at the age of {1}", item.Count, item.Age);
- foreach (var student in item.Students)
- {
- Console.WriteLine(student.Name);
- }
- }
- }
- public class GroupedStudents
- {
- public int Age { get; set; }
- public int Count { get; set; }
- public IGrouping<int, Student> Students { get; set; }
- }
- public class Student
- {
- public Student(int age = 16, string name = "")
- {
- this.Age = age;
- this.Name = name;
- }
- public int Age { get; set; }
- public string Name { get; set; }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement