Alexander0202

Sorting

Apr 9th, 2018
342
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 7.07 KB | None | 0 0
  1. /*Zhigunov. Task 3.
  2.  * 3. Подсчитать количество студентов:
  3.  * а) учащихся на 5 и 6 курсах;
  4.  * б) подсчитать сколько студентов в возрасте от 18 до 20 лет на каком курсе учатся(частотный массив);
  5.  * в) отсортировать список по возрасту студента;
  6.  * г) *отсортировать список по курсу и возрасту студента.
  7.  * Дополнительное домашнее задание
  8. */
  9. using System;
  10. using System.Collections.Generic;
  11. using System.Linq;
  12. using System.Text;
  13. using System.Threading.Tasks;
  14. using System.IO;
  15.  
  16. namespace Task3
  17. {
  18.     class Student
  19.     {
  20.         string lastName;
  21.         string firstName;
  22.         string univercity;
  23.         string faculty;
  24.         public int course;
  25.         public string department;
  26.         public int group;
  27.         public string city;
  28.         public int age;
  29.  
  30.         public string LastName
  31.         {
  32.             get { return lastName; }
  33.         }
  34.  
  35.         public string FirstName
  36.         {
  37.             get { return firstName; }
  38.         }
  39.  
  40.         public string Univercity
  41.         {
  42.             get { return univercity; }
  43.         }
  44.  
  45.         public string Faculty
  46.         {
  47.             get { return faculty; }
  48.         }
  49.  
  50.  
  51.  
  52.         //Создаем конструктор
  53.         public Student(string firstName, string lastName, string univercity, string faculty, string department, int age, int course, int group, string city)
  54.         {
  55.             this.lastName = lastName;
  56.             this.firstName = firstName;
  57.             this.univercity = univercity;
  58.             this.faculty = faculty;
  59.             this.department = department;
  60.             this.course = course;
  61.             this.age = age;
  62.             this.group = group;
  63.             this.city = city;
  64.         }
  65.  
  66.         public override string ToString()
  67.         {
  68.             return String.Format("{0,20}{1,15}{2,15}{3,15}{4,15}{5,15}", firstName, lastName, age, course, group, city);
  69.         }
  70.     }
  71.     class Task3
  72.     {
  73.         static void CalcStud(List<Student> list)
  74.         {
  75.             //list.Sort(MyMethod2); //already sorted by course
  76.             List<Student> newlist = new List<Student>();
  77.             Student t;
  78.             int[] courseFreq = new int[7]; //made 6 instead of 5 just for simplicity
  79.             for (int i = 0; i < list.Count; i++)
  80.             {
  81.                 t = list[i];
  82.                 if (t.age >= 18 && t.age <= 20)
  83.                 {
  84.                     newlist.Add(t);
  85.                     courseFreq[t.course]++;
  86.                 }
  87.             }
  88.             Console.WriteLine("У нас " + newlist.Count + " студентов в возрасте 18-20");
  89.             Console.WriteLine("1 курс: " + courseFreq[1]);
  90.             Console.WriteLine("2 курс: " + courseFreq[2]);
  91.             Console.WriteLine("3 курс: " + courseFreq[3]);
  92.             Console.WriteLine("4 курс: " + courseFreq[4]);
  93.             Console.WriteLine("5 курс: " + courseFreq[5]);
  94.             Console.WriteLine("6 курс: " + courseFreq[6]);
  95.  
  96.         }
  97.         static int MyMethod(Student st1, Student st2)//Создаем метод для сравнения для экземпляров по возрасту
  98.         {
  99.             if (st1.age > st2.age) return 1;
  100.             if (st1.age < st2.age) return -1;
  101.             return 0;
  102.         }
  103.         static int MyMethod2(Student st1, Student st2)//Создаем метод для сравнения для экземпляров по номеру курса
  104.         {
  105.             if (st1.course > st2.course) return 1;
  106.             if (st1.course < st2.course) return -1;
  107.             return 0;
  108.         }
  109.  
  110.         static int SortByAgeAndCourse(Student st1, Student st2)
  111.         {
  112.             if (st1.age > st2.age) return 1;
  113.             if (st1.age < st2.age) return -1;
  114.             if (st1.course > st2.course) return 1;
  115.             if (st1.course < st2.course) return -1;
  116.             return 0;
  117.         }
  118.  
  119.         static void Main(string[] args)
  120.         {
  121.             int magistr = 0;
  122.             int bakalavr = 0;
  123.             //Создаем список студентов
  124.             List<Student> list = new List<Student>();
  125.             StreamReader sr = null;
  126.             try
  127.             {
  128.                 sr = new StreamReader("students_1.csv");
  129.                 Student t;
  130.                 string temp = "";
  131.                 string[] s;
  132.                 while (!sr.EndOfStream)
  133.                 {
  134.                     try
  135.                     {
  136.                         temp = sr.ReadLine();
  137.                         s = temp.Split(';');
  138.                         //Добавляем в список новый экземляр класса Student
  139.                         t = new Student(s[0], s[1], s[2], s[3], s[4], int.Parse(s[5]), Convert.ToInt32(s[6]), int.Parse(s[7]), s[8]);
  140.                         list.Add(t);
  141.                         //Одновременно подсчитываем кол-во бакалавров и магистров
  142.                         if (t.course < 5) bakalavr++; else magistr++;
  143.                     }
  144.                     catch (ArgumentNullException e)
  145.                     {
  146.  
  147.                     }
  148.                     catch (ArgumentException exc)
  149.                     {
  150.  
  151.                     }
  152.                     catch (Exception e)
  153.                     {
  154.                         //throw new Exception();
  155.                         Console.WriteLine(e.Message);
  156.                         Console.WriteLine(temp);
  157.                     }
  158.                 }
  159.             }
  160.             catch
  161.             {
  162.  
  163.             }
  164.             finally//try
  165.             {
  166.                 if (sr != null) sr.Close();
  167.             }
  168.            
  169.             Console.WriteLine("Всего студентов:" + list.Count);
  170.             Console.WriteLine("Учащихся на 5 и 6 курсах (магистров):{0}", magistr); //учащихся на 5 и 6 курсах;
  171.  
  172.             List<Student> list2 = new List<Student>(); //Lets make copy of original list to compare results
  173.             list2 = list;
  174.  
  175.             list2.Sort(SortByAgeAndCourse); //sort using method, proposed at lecture
  176.  
  177.             list.Sort(MyMethod); //отсортировать список по возрасту студента;
  178.             list.Sort(MyMethod2); //теперь список будет отсоертирован и по курсу
  179.  
  180.             if (list.ToArray() == list2.ToArray())
  181.             {
  182.                 Console.WriteLine("Yes, both methods return same result");
  183.             }
  184.             else
  185.             {
  186.                 Console.WriteLine("No, methods return different result");
  187.             }
  188.  
  189.             CalcStud(list);//подсчитать сколько студентов в возрасте от 18 до 20 лет на каком курсе учатся(частотный массив);
  190.             Console.ReadKey();
  191.         }
  192.     }
  193.    
  194. }
Advertisement
Add Comment
Please, Sign In to add comment