Сортировка списка - C# (184771)
Формулировка задачи:
Имеется класс Contact
Наследуемый от него:
И, собственно, мне надо во втором (Contacts) классе реализовать сортировку в алфавитном порядке по результату метода FIO; Пробовал через интерфейсы, через методы расширения - не получилось, почему - хз)
public class Contact
{
public string Surname { get; set; }
public string Name { get; set; }
public string LastName { get; set; }
public string Number { get; set; }
public override string ToString()
{
return $"{this.Name} : {this.Number}";
}
public string FIO()
{
return $"Фамилия {this.Surname} Имя {this.Name} Отчество {this.LastName}";
}public class Contacts : List<Contact>
{
public List<Contact> contactsprop { get; set; }Решение задачи: «Сортировка списка»
textual
Листинг программы
using System;
using System.Collections.Generic;
using System.Linq;
namespace Cont
{
class Program
{
static void Main(string[] args)
{
Contacts conts = new Contacts();
conts.Add(new Contact("Иванов", "Иван", "Иванович", "000232"));
conts.Add(new Contact("Петров", "Иван", "Иванович", "000232"));
conts.Add(new Contact("Сидоров", "Иван", "Иванович", "000232"));
conts.Add(new Contact("Антонов", "Ашот", "Исакович", "000232"));
conts.Add(new Contact("Иванов", "Олег", "Петрович", "000232"));
conts.Add(new Contact("Антонов", "Ашот", "Иванович", "000232"));
conts.Add(new Contact("Иванов", "Иван", "Антонович", "000232"));
foreach (Contact cont in conts.GetContacts())
Console.WriteLine(cont.FIO);
Console.WriteLine();
Console.WriteLine();
conts.SortByFIO();
foreach (Contact cont in conts.GetContacts())
Console.WriteLine(cont.FIO);
Console.ReadLine();
}
}
public class Contact
{
public string Surname { get; set; }
public string Name { get; set; }
public string LastName { get; set; }
public string Number { get; set; }
public Contact(string surname, string name, string lastname, string number)
{
Surname = surname;
Name = name;
LastName = lastname;
Number = number;
}
public override string ToString()
{
return string.Format("{0}:{1}",this.Name,this.Number);
}
public string FIO
{
get { return string.Format("{0} {1} {2}", this.Surname, this.Name, this.LastName); }
}
}
public class Contacts
{
List<Contact> contactsprop;
public Contacts()
{
contactsprop = new List<Contact>();
}
public void Add(Contact contact)
{
contactsprop.Add(contact);
}
public IEnumerable<Contact> GetContacts()
{
foreach (Contact contact in contactsprop)
{
yield return contact;
}
}
public void SortByFIO()
{
contactsprop = contactsprop.OrderBy(x => x.Surname).ThenBy(y => y.Name).ThenBy(z => z.LastName).ToList();
}
}
}