Advertisement
Guest User

Untitled

a guest
Mar 28th, 2015
216
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.72 KB | None | 0 0
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5.  
  6. namespace ExamPreparation
  7. {
  8.     class Program
  9.     {
  10.         static void Main()
  11.         {
  12.             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") };
  13.  
  14.             IEnumerable<GroupedStudents> groupedStudentsByAge = oldStudents
  15.                 .GroupBy(s => s.Age)
  16.                 .OrderByDescending(g => g.Key)
  17.                 .Select(g => new GroupedStudents
  18.                 {
  19.                     Age = g.Key,
  20.                     Count = g.Count(),
  21.                     Students = g
  22.                 });
  23.  
  24.             PrintGroupedStudent(groupedStudentsByAge);
  25.         }
  26.  
  27.         public static void PrintGroupedStudent(IEnumerable<GroupedStudents> groupedStudents )
  28.         {
  29.             foreach (var item in groupedStudents)
  30.             {
  31.                 Console.WriteLine("There are {0} students at the age of {1}", item.Count, item.Age);
  32.                 foreach (var student in item.Students)
  33.                 {
  34.                     Console.WriteLine(student.Name);
  35.                 }
  36.             }
  37.         }
  38.  
  39.         public class GroupedStudents
  40.         {
  41.             public int Age { get; set; }
  42.  
  43.             public int Count { get; set; }
  44.  
  45.             public IGrouping<int, Student> Students { get; set; }
  46.         }
  47.  
  48.      
  49.     public class Student
  50.     {
  51.         public Student(int age = 16, string name = "")
  52.         {
  53.             this.Age = age;
  54.             this.Name = name;
  55.         }
  56.  
  57.         public int Age { get; set; }
  58.         public string Name { get; set; }
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement