Levi0227

2. félév 3. óra (otthon) IComperble

Mar 4th, 2024
938
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.64 KB | Source Code | 0 0
  1. namespace ComparableExample
  2. {
  3.     internal class Program
  4.     {
  5.         static void Main(string[] args)
  6.         {
  7.             Student[] students =
  8.             {
  9.                 new Student() { NeptunCode = "asd123", Semester = 3 },
  10.                 new Student() { NeptunCode = "fbg456", Semester = 1 },
  11.                 new Student() { NeptunCode = "wrez41", Semester = 2 },
  12.                 new Student() { NeptunCode = "fdgh10", Semester = 5 },
  13.                 new Student() { NeptunCode = "egh333", Semester = 2 },
  14.                 new Student() { NeptunCode = "qed786", Semester = 4 },
  15.             };
  16.  
  17.             Array.Sort(students);
  18.  
  19.             foreach (Student student in students)
  20.             {
  21.                 Console.WriteLine(student);
  22.             }
  23.         }
  24.     }
  25. }
  26.  
  27. ------------------------------------------------------
  28. Osztály
  29. ------------------------------------------------------
  30.  
  31. using System;
  32. using System.Collections.Generic;
  33. using System.Linq;
  34. using System.Text;
  35. using System.Threading.Tasks;
  36.  
  37. namespace ComparableExample
  38. {
  39.     internal class Student : IComparable
  40.     {
  41.         public int Semester { get; set; }
  42.         public string NeptunCode{ get; set; }
  43.  
  44.         public int CompareTo(object obj)
  45.         {
  46.             Student other = obj as Student;
  47.  
  48.             if (Semester == other.Semester)
  49.             {
  50.                 return NeptunCode.CompareTo(other.NeptunCode);
  51.             }
  52.             if (Semester < other.Semester) return -1;
  53.             return 0;
  54.         }
  55.  
  56.         public override string ToString()
  57.         {
  58.             return $"{NeptunCode} ({Semester})";
  59.         }
  60.     }
  61. }
  62.  
Advertisement
Add Comment
Please, Sign In to add comment