Получить максимальный объект по свойству - C#

Узнай цену своей работы

Формулировка задачи:

Допустим есть такой код:
Листинг программы
  1. using System;
  2. using System.Linq;
  3. using System.Collections;
  4. using System.Collections.Generic;
  5. public class Employee {
  6. public int birthYear;
  7. public string firstName;
  8. public string lastName;
  9. public static Employee[] GetEmployees() {
  10. Employee[] actors = new Employee[] {
  11. new Employee { birthYear = 1964, firstName = "K", lastName = "R" },
  12. new Employee { birthYear = 1968, firstName = "O", lastName = "W" },
  13. new Employee { birthYear = 1960, firstName = "J", lastName = "S" },
  14. new Employee { birthYear = 1964, firstName = "S", lastName = "B" },
  15. };
  16. return (actors);
  17. }
  18. }
  19. public class MainClass {
  20. public static void Main() {
  21. int youngestEmployeeAge = Employee.GetEmployees().Max(a => a.birthYear);
  22. Console.WriteLine(youngestEmployeeAge);
  23. }
  24. }
он вернет int год рождения, НО как использовать Max чтобы по максимальному году он возвращал сам объект

Employee

? Логически именно так и должен был работать метод Max из коробки((

Решение задачи: «Получить максимальный объект по свойству»

textual
Листинг программы
  1.     public class Employee : IComparable<Employee>
  2.     {
  3.         public int birthYear;
  4.         public string firstName;
  5.         public string lastName;
  6.  
  7.         public static Employee[] GetEmployees()
  8.         {
  9.             Employee[] actors = new Employee[] {
  10.                 new Employee { birthYear = 1964, firstName = "K", lastName = "R" },
  11.                 new Employee { birthYear = 1968, firstName = "O", lastName = "W" },
  12.                 new Employee { birthYear = 1960, firstName = "J", lastName = "S" },
  13.                 new Employee { birthYear = 1964, firstName = "S", lastName = "B" },
  14.             };
  15.             return (actors);
  16.         }
  17.  
  18.         public int CompareTo(Employee other)
  19.         {
  20.             return birthYear.CompareTo(other.birthYear);
  21.         }
  22.     }
  23.  
  24.             Employee youngestEmployeeAge = Employee.GetEmployees().Max();
  25.             Console.WriteLine(youngestEmployeeAge.birthYear);

ИИ поможет Вам:


  • решить любую задачу по программированию
  • объяснить код
  • расставить комментарии в коде
  • и т.д
Попробуйте бесплатно

Оцени полезность:

8   голосов , оценка 4.25 из 5

Нужна аналогичная работа?

Оформи быстрый заказ и узнай стоимость

Бесплатно
Оформите заказ и авторы начнут откликаться уже через 10 минут
Похожие ответы