PIbd-11.Basalov.A.D.LabWork08.Simple #15

Closed
Tonby73 wants to merge 6 commits from LabWork8 into LabWork7
23 changed files with 631 additions and 579 deletions

View File

@ -1 +0,0 @@
#include "Data_Structure.h"

View File

@ -1,42 +0,0 @@
//#include <stdio.h>
//#include <stdlib.h>
//
//#pragma once
//
//struct Node {
// int data;
// Node* next;
//};
//
//class Data_Structure
//{
//private:
// Node* head;
// struct Node {
// int data;
// Node* next;
// };
//public:
// Data_Structure(){
// head = NULL;
// }
// void addNode(int val){
// Node* newNode = new Node;
// newNode->data = val;
// newNode->next = head;
// head = newNode;
//
//
// }
// void printList() {
// Node* currentNode = head;
// while (currentNode->next != NULL) {
// printf("%d", currentNode->data);
// currentNode = currentNode->next;
//
// }
//
//
// }
//};
//

View File

@ -1,31 +0,0 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.7.34024.191
MinimumVisualStudioVersion = 10.0.40219.1
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Lab_1", "Lab_1.vcxproj", "{B3B62C1B-E8D8-4038-8DFD-248406A48EE2}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Release|x64 = Release|x64
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{B3B62C1B-E8D8-4038-8DFD-248406A48EE2}.Debug|x64.ActiveCfg = Debug|x64
{B3B62C1B-E8D8-4038-8DFD-248406A48EE2}.Debug|x64.Build.0 = Debug|x64
{B3B62C1B-E8D8-4038-8DFD-248406A48EE2}.Debug|x86.ActiveCfg = Debug|Win32
{B3B62C1B-E8D8-4038-8DFD-248406A48EE2}.Debug|x86.Build.0 = Debug|Win32
{B3B62C1B-E8D8-4038-8DFD-248406A48EE2}.Release|x64.ActiveCfg = Release|x64
{B3B62C1B-E8D8-4038-8DFD-248406A48EE2}.Release|x64.Build.0 = Release|x64
{B3B62C1B-E8D8-4038-8DFD-248406A48EE2}.Release|x86.ActiveCfg = Release|Win32
{B3B62C1B-E8D8-4038-8DFD-248406A48EE2}.Release|x86.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {FF15C0FB-D559-46A6-B4E8-E461B8F5C363}
EndGlobalSection
EndGlobal

View File

@ -1,139 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<VCProjectVersion>17.0</VCProjectVersion>
<Keyword>Win32Proj</Keyword>
<ProjectGuid>{b3b62c1b-e8d8-4038-8dfd-248406a48ee2}</ProjectGuid>
<RootNamespace>Lab1</RootNamespace>
<WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="Data_Structure.cpp" />
<ClCompile Include="Source.cpp" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="Data_Structure.h" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@ -1,30 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="Исходные файлы">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
<Filter Include="Файлы заголовков">
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
<Extensions>h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd</Extensions>
</Filter>
<Filter Include="Файлы ресурсов">
<UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
</Filter>
</ItemGroup>
<ItemGroup>
<ClCompile Include="Source.cpp">
<Filter>Исходные файлы</Filter>
</ClCompile>
<ClCompile Include="Data_Structure.cpp">
<Filter>Исходные файлы</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ClInclude Include="Data_Structure.h">
<Filter>Файлы заголовков</Filter>
</ClInclude>
</ItemGroup>
</Project>

View File

@ -1,199 +0,0 @@
/*
Âàðèàíò 4
ÀÒÄ - ÑÒÅÊ
ÑÄ - Îäíîñâÿçàííûé ñïèñîê
Îáúåêòíàÿ îáëàòü - Ñòóäåíòû, îáùèå äàííûå
Ñîðòèðîâêà ñëèÿíèåì, øåéêåðîì
*/
#include <stdio.h>
#include <stdlib.h>
#include "Data_Structure.h"
int unsorted_array[10] = { 2, 5, 1,8,3,4,7,6,9,0 };
int arr[10] = { 2, 5, 1,8,3,4,7,6,9,0 };
int n = 10;
void Buble_sort() {
for (int i = 0; i < n; i++) {
for (int j = n - 1; j > i; j--) {
if (arr[j - 1] > arr[j]) {
int temp = arr[j];
arr[j] = arr[j - 1];
arr[j - 1] = temp;
}
}
}
}
void Merge(int arr[], int begin, int end) {
int mid = begin + (end - begin) / 2;
int i = begin;
int j = mid + 1;
int d[11] = { 0 };
int k = 0;
while (i <= mid && j <= end) {
if (arr[i] <= arr[j]) {
d[k] = arr[i];
i++;
}
else {
d[k] = arr[j];
j++;
}
k++;
}
while (i <= mid) {
d[k] = arr[i];
k++;
i++;
}
while (j <= end) {
d[k] = arr[j];
k++;
j++;
}
for (i = 0; i < k; i++) {
arr[begin + i] = d[i];
}
}
void Merge_sort(int* arr, int left, int right) {
int temp = 0;
if (left < right) {
if (right - left == 1) {
if (arr[left] > arr[right]) {
temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
}
}
else {
Merge_sort(arr, left, (right - left) / 2);
Merge_sort(arr, left + (right - left) / 2 + 1, right);
Merge(arr, left, right);
}
}
}
void Shake_sort() {
int direction = 0;
int left = arr[0];
int left_index = 0;
int right = arr[n];
int right_index = n;
for (int _ = 0; _ < n - 1; _++) {
if (direction == 0) {
for (int i = left_index; i < right_index - 1; i++) {
if (arr[i] > arr[i + 1]) {
int temp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = temp;
}
}
if (right != arr[right_index]) {
for (int i = n; i > 0; i--) {
if (arr[i] == right) {
right_index = i;
}
}
}
direction = 1;
}
else {
for (int j = right_index; j > left_index; j--) {
if (arr[j] < arr[j - 1]) {
int temp1 = arr[j];
arr[j] = arr[j - 1];
arr[j - 1] = temp1;
}
}
if (left != arr[left_index]) {
for (int i = 0; i < n; i++) {
if (arr[i] == left) {
left_index = i;
}
}
}
}
direction = 0;
}
}
void print_list() {
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
struct Node {
int student_year;
int student_group;
struct Node* next;
};
struct Node* first = NULL;
void s_addToHead(int year, int group) {
struct Node* NewNode = (struct Node*)malloc(sizeof(NewNode));
NewNode->student_year = year;
NewNode->student_group = group;
NewNode->next = first;
first = NewNode;
}
void s_deleteFromHead() {
struct Node* DelNode = first;
int val1 = DelNode->student_year;
int val2 = DelNode->student_group;
first = first->next;
printf("****|PI-%d, %d| - Deleted\n", val2, val1);
}
void s_print() {
struct Node* i = first;
while (i) {
printf("|PI-%d, %d|\n", i->student_group, i->student_year);
i = i->next;
}
}
int main() {
s_addToHead(2020, 12);
s_addToHead(2021, 13);
s_addToHead(2022, 14);
s_addToHead(2024, 15);
s_print();
printf("------------------------\n");
s_deleteFromHead();
s_print();
print_list();
Shake_sort();
//Merge_sort(arr, 0, n - 1);
print_list();
//Data_structure newStructure;
return 0;
}

View File

@ -1,4 +1,5 @@
using ProjectElectricLocomotive.Drawnings;
using ProjectElectricLocomotive.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
@ -62,7 +63,7 @@ public abstract class AbstractCompany
public static int operator +(AbstractCompany company, DrawningLocomotive locomotive)
{
return company._collection.Insert(locomotive);
return company._collection?.Insert(locomotive, new DrawiningLocomotiveEqutables()) ?? throw new DrawningEqutablesException();
}
/// <summary>
/// Перегрузка оператора удаления для класса
@ -106,6 +107,12 @@ public abstract class AbstractCompany
return bitmap;
}
/// <summary>
/// Сортировка
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
public void Sort(IComparer<DrawningLocomotive?> comparer) => _collection?.CollectionSort(comparer);
/// <summary>
/// Вывод заднего фона
/// </summary>

View File

@ -0,0 +1,83 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectElectricLocomotive.CollectionGenericObjects
{
/// <summary>
/// Класс, хранящиий информацию по коллекции
/// </summary>
public class CollectionInfo : IEquatable<CollectionInfo>
{
/// <summary>
/// Название
/// </summary>
public string Name { get; private set; }
/// <summary>
/// Тип
/// </summary>
public CollectionType CollectionType { get; private set; }
/// <summary>
/// Описание
/// </summary>
public string Description { get; private set; }
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly string _separator = "-";
/// <summary>
/// Конструктор
/// </summary>
/// /// <param name="name">Название</param>
/// <param name="collectionType">Тип</param>
/// <param name="description">Описание</param>
public CollectionInfo(string name, CollectionType collectionType, string
description)
{
Name = name;
CollectionType = collectionType;
Description = description;
}
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="data">Строка</param>
/// <returns>Объект или null</returns>
public static CollectionInfo? GetCollectionInfo(string data)
{
string[] strs = data.Split(_separator,
StringSplitOptions.RemoveEmptyEntries);
if (strs.Length < 1 || strs.Length > 3)
{
return null;
}
return new CollectionInfo(strs[0],
(CollectionType)Enum.Parse(typeof(CollectionType), strs[1]), strs.Length > 2 ?
strs[2] : string.Empty);
}
public override string ToString()
{
return Name + _separator + CollectionType + _separator + Description;
}
public bool Equals(CollectionInfo? other)
{
return Name == other?.Name;
}
public override bool Equals(object? obj)
{
return Equals(obj as CollectionInfo);
}
public override int GetHashCode()
{
return Name.GetHashCode();
}
public bool IsEmpty()
{
if (string.IsNullOrEmpty(Name) && CollectionType != CollectionType.None) return true;
return false;
}
}
}

View File

@ -27,22 +27,23 @@ public interface ICollectionGenericObjects<T>
/// </summary>
/// <param name="obj">Добавляемый объект</param>
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
int Insert(T obj);
/// <summary>
/// Добавление объекта в коллекцию
/// </summary>
/// <param name="obj">Добавляемый объект</param>
/// <param name="comparer">Cравнение двух объектов</param>
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
int Insert(T obj, IEqualityComparer<T?>? comparer = null);
/// <summary>
/// Добавление объекта в коллекцию на конкретную позицию
/// </summary>
/// <param name="obj">Добавляемый объект</param>
/// <param name="position">Позиция</param>
/// <param name="comparer">Cравнение двух объектов</param>
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
int Insert(T obj, int position);
int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null);
/// <summary>
/// Удаление объекта из коллекции с конкретной позиции
/// </summary>
/// <param name="position">Позиция</param>
/// <returns>true - удаление прошло удачно, false - удаление не удалось</returns>
T Remove(int position);
T Remove(int position);
/// <summary>
/// Получение объекта по позиции
/// </summary>
@ -60,4 +61,11 @@ T Remove(int position);
/// </summary>
/// <returns>Поэлементый вывод элементов коллекции</returns>
IEnumerable<T?> GetItems();
/// <summary>
/// Сортировка коллекции
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
void CollectionSort(IComparer<T?> comparer);
}

View File

@ -55,21 +55,46 @@ namespace ProjectElectricLocomotive.CollectionGenericObjects
return _collection[position];
}
public int Insert(T obj)
public int Insert(T obj, IEqualityComparer<T?>? comparer = null)
{
// выброс ошибки если переполнение
//выброс ошибки если такой объект уже есть в коллекции
if(comparer != null)
{
for(int i = 0; i < Count; i++)
Review

У списка есть метод Contains для проверки

У списка есть метод Contains для проверки
{
if (comparer.Equals(_collection[i], obj))
{
throw new CollectionDuplicateException(obj);
}
}
}
if (Count == _maxCount) throw new CollectionOverflowException(Count);
_collection.Add(obj);
return Count;
}
public int Insert(T obj, int position)
public int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
{
// проверка, что не превышено максимальное количество элементов
// проверка позиции
// вставка по позиции
// выброс ошибки, если переполнение
// выброс ошибки если выход за границу
//выброс ошибки если такой объект уже есть в коллекции
if (comparer != null)
{
for (int i = 0; i < Count; i++)
{
if (comparer.Equals(_collection[i], obj))
{
throw new CollectionDuplicateException(obj);
}
}
}
if (Count == _maxCount) throw new CollectionOverflowException(Count);
@ -98,5 +123,11 @@ namespace ProjectElectricLocomotive.CollectionGenericObjects
yield return _collection[i];
}
}
public void CollectionSort(IComparer<T?> comparer)
{
_collection.Sort(comparer);
// throw new NotImplementedException();
}
}
}

View File

@ -56,11 +56,24 @@ namespace ProjectElectricLocomotive.CollectionGenericObjects
if (_collection[position] == null) throw new ObjectNotFoundException(position);
return _collection[position];
}
public int Insert(T obj)
public int Insert(T obj, IEqualityComparer<T?>? comparer = null)
{
// вставка в свободное место набора
// выброс ошибки, если переполнение
//выброс ошибки, если выход за границы массива
//выброс ошибки если такой объект уже есть в коллекции
if(comparer != null)
{
for(int i = 0; i < Count; i++)
{
if (comparer.Equals(_collection[i], obj))
{
throw new CollectionDuplicateException(obj);
}
}
}
for (int i = 0; i < Count; i++)
{
if (_collection[i] == null)
@ -72,7 +85,7 @@ namespace ProjectElectricLocomotive.CollectionGenericObjects
throw new CollectionOverflowException(Count);
}
public int Insert(T obj, int position)
public int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
{
// проверка позиции
// проверка, что элемент массива по этой позиции пустой, если нет, то
@ -80,7 +93,18 @@ namespace ProjectElectricLocomotive.CollectionGenericObjects
// вставка
//выброс ошибки, если переполнение
//выброс ошибки, если выход за границы массива
//выброс ошибки если такой объект уже есть в коллекции
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
if(comparer != null)
{
for(int i = 0; i < Count; i++)
{
if (comparer.Equals(_collection[i], obj))
{
throw new CollectionDuplicateException(obj);
}
}
}
if (_collection[position] == null)
{
@ -128,5 +152,11 @@ namespace ProjectElectricLocomotive.CollectionGenericObjects
yield return _collection[i];
}
}
public void CollectionSort(IComparer<T?> comparer)
{
Array.Sort(_collection, comparer);
// throw new NotImplementedException();
}
}
}

View File

@ -19,64 +19,58 @@ where T : DrawningLocomotive
/// <summary>
/// Словарь (хранилище) с коллекциями
/// </summary>
readonly Dictionary<string, ICollectionGenericObjects<T>> _storages;
readonly Dictionary<CollectionInfo, ICollectionGenericObjects<T>> _storages;
/// <summary>
/// Возвращение списка названий коллекций
/// </summary>
public List<string> Keys => _storages.Keys.ToList();
public List<CollectionInfo> Keys => _storages.Keys.ToList();
/// <summary>
/// Конструктор
/// </summary>
public StorageCollection()
{
_storages = new Dictionary<string, ICollectionGenericObjects<T>>();
_storages = new Dictionary<CollectionInfo, ICollectionGenericObjects<T>>();
}
/// <summary>
/// Добавление коллекции в хранилище
/// </summary>
/// <param name="name">Название коллекции</param>
/// <param name="collectionType">тип коллекции</param>
public void AddCollection(string name, CollectionType collectionType)
public void AddCollection(CollectionInfo collectionInfo)
{
if(collectionType != CollectionType.None && !_storages.ContainsKey(name)) {
if(collectionType == CollectionType.List)
{
_storages.Add(name, new ListGenericObjects<T>());
}
else if (collectionType == CollectionType.Massive)
{
_storages.Add(name, new MassiveGenericObjects<T>());
}
}
// TODO проверка, что name не пустой и нет в словаре записи с таким ключом
// TODO Прописать логику для добавления
// TODO Прописать логику для добавления
if (_storages.ContainsKey(collectionInfo)) throw new CollectionExistsException(collectionInfo);
if (collectionInfo.CollectionType == CollectionType.None)
throw new CollectionNoTypeException("Отсутсвует тип коллекции");
if (collectionInfo.CollectionType == CollectionType.Massive)
_storages[collectionInfo] = new MassiveGenericObjects<T>();
else if (collectionInfo.CollectionType == CollectionType.List)
_storages[collectionInfo] = new ListGenericObjects<T>();
}
/// <summary>
/// Удаление коллекции
/// </summary>
/// <param name="name">Название коллекции</param>
public void DelCollection(string name)
public void DelCollection(CollectionInfo collectionInfo)
{
if (_storages.ContainsKey(name))
{
_storages.Remove(name);
}
// TODO Прописать логику для удаления коллекции
if (_storages.ContainsKey(collectionInfo))
_storages.Remove(collectionInfo);
}
/// <summary>
/// Доступ к коллекции
/// </summary>
/// <param name="name">Название коллекции</param>
/// <returns></returns>
public ICollectionGenericObjects<T>? this[string name]
public ICollectionGenericObjects<T>? this[CollectionInfo collectionInfo]
{
get
{
if (_storages.ContainsKey(name))
{
return _storages[name];
}
// TODO Продумать логику получения объекта
if (_storages.ContainsKey(collectionInfo))
return _storages[collectionInfo];
return null;
}
}
@ -101,49 +95,52 @@ where T : DrawningLocomotive
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
/// <summary>
/// Сохранение информации по автомобилям в хранилище в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
public void SaveData(string filename)
{
if (_storages.Count == 0)
{
if (_storages.Count == 0)
{
throw new Exception("В хранилище отсутствуют коллекции для сохранения");
throw new EmptyFileExeption();
}
}
if (File.Exists(filename))
if (File.Exists(filename))
{
File.Delete(filename);
}
using (StreamWriter writer = new StreamWriter(filename))
{
writer.Write(_collectionKey);
foreach (KeyValuePair<CollectionInfo, ICollectionGenericObjects<T>> value in _storages)
{
File.Delete(filename);
}
using (StreamWriter writer = new StreamWriter(filename))
{
writer.Write(_collectionKey);
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages)
StringBuilder sb = new();
sb.Append(Environment.NewLine);
// не сохраняем пустые коллекции
if (value.Value.Count == 0)
{
StringBuilder sb = new(); // построитель строк
sb.Append(Environment.NewLine);
// не сохраняем пустые коллекции
if (value.Value.Count == 0)
continue;
}
sb.Append(value.Key);
sb.Append(_separatorForKeyValue);
sb.Append(value.Value.MaxCount);
sb.Append(_separatorForKeyValue);
foreach (T? item in value.Value.GetItems())
{
string data = item?.GetDataForSave() ?? string.Empty;
if (string.IsNullOrEmpty(data))
{
continue;
}
sb.Append(value.Key);
sb.Append(_separatorForKeyValue);
sb.Append(value.Value.GetCollectionType);
sb.Append(_separatorForKeyValue);
sb.Append(value.Value.MaxCount);
sb.Append(_separatorForKeyValue);
foreach (T? item in value.Value.GetItems())
{
string data = item?.GetDataForSave() ?? string.Empty;
if (string.IsNullOrEmpty(data))
{
continue;
}
sb.Append(data);
sb.Append(_separatorItems);
}
writer.Write(sb);
sb.Append(data);
sb.Append(_separatorItems);
}
writer.Write(sb);
}
}
}
@ -155,60 +152,60 @@ where T : DrawningLocomotive
// /// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
throw new Exception("Файл не существует");
throw new FileNotFoundException(filename);
}
using (StreamReader fs = File.OpenText(filename))
{
string str = fs.ReadLine();
if (str == null || str.Length == 0)
if (string.IsNullOrEmpty(str))
{
throw new Exception("В файле нет данных");
throw new EmptyFileExeption(filename);
}
if (!str.StartsWith(_collectionKey))
{
throw new Exception("В файле неверные данные");
throw new FileFormatException(filename);
}
_storages.Clear();
string strs = "";
while ((strs = fs.ReadLine()) != null)
{
string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 4)
if (record.Length != 3)
{
continue;
}
CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]);
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
if (collection == null)
{
throw new Exception("Не удалось создать коллекцию");
}
collection.MaxCount = Convert.ToInt32(record[2]);
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
CollectionInfo? collectionInfo =
CollectionInfo.GetCollectionInfo(record[0]) ??
throw new CollectionNoInfoException("Не удалось определить информацию коллекции:" + record[0]);
ICollectionGenericObjects<T>? collection =
StorageCollection<T>.CreateCollection(collectionInfo.CollectionType) ??
throw new CollectionNoTypeException("Не удалось определить тип коллекции:" + record[1]);
collection.MaxCount = Convert.ToInt32(record[1]);
string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
if (elem?.CreateDrawningLocomotive() is T truck)
if (elem?.CreateDrawningLocomotive() is T macine)
{
try
{
if (collection.Insert(truck) == -1)
{
throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]);
}
collection.Insert(macine);
}
catch (CollectionOverflowException ex)
catch (Exception ex)
{
throw new Exception("Коллекция переполнена", ex);
throw new FileFormatException(filename, ex);
}
}
}
_storages.Add(record[0], collection);
_storages.Add(collectionInfo, collection);
}
}
}

View File

@ -0,0 +1,70 @@
using ProjectElectricLocomotive.Entities;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectElectricLocomotive.Drawnings;
/// <summary>
/// Реализация сравнения двух объектов класса-прорисовки
/// </summary>
public class DrawiningLocomotiveEqutables : IEqualityComparer<DrawningLocomotive?>
{
public bool Equals(DrawningLocomotive? x, DrawningLocomotive? y)
{
if (x == null || x.EntityLocomotive == null)
{
return false;
}
if (y == null || y.EntityLocomotive == null)
{
return false;
}
if (x.GetType().Name != y.GetType().Name)
{
return false;
}
if (x.EntityLocomotive.Speed != y.EntityLocomotive.Speed)
{
return false;
}
if (x.EntityLocomotive.Weight != y.EntityLocomotive.Weight)
{
return false;
}
if (x.EntityLocomotive.BodyColor != y.EntityLocomotive.BodyColor)
{
return false;
}
if (x is DrawningElectricLocomotive && y is DrawningElectricLocomotive)
{
if(((EntityElectricLocomotive) x.EntityLocomotive).AdditionalColor != ((EntityElectricLocomotive)y.EntityLocomotive).AdditionalColor)
Review

Зачем неоднократные преобразования, что мешает сделать это один раз?

Зачем неоднократные преобразования, что мешает сделать это один раз?
{
return false;
}
if (((EntityElectricLocomotive)x.EntityLocomotive).Pantograph != ((EntityElectricLocomotive)y.EntityLocomotive).Pantograph)
{
return false;
}
if (((EntityElectricLocomotive)x.EntityLocomotive).BatteryStorage != ((EntityElectricLocomotive)y.EntityLocomotive).BatteryStorage)
{
return false;
}
// TODO доделать логику сравнения дополнительных параметров
}
return true;
}
public int GetHashCode([DisallowNull] DrawningLocomotive obj)
{
return obj.GetHashCode();
}
}

View File

@ -0,0 +1,45 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectElectricLocomotive.Drawnings
{
/// <summary>
/// Сравнение по цвету, скорости, весу
/// </summary>
public class DrawningLocomotiveCompareByColor : IComparer<DrawningLocomotive?>
{
public int Compare(DrawningLocomotive? x, DrawningLocomotive? y)
{
if (x == null && y == null) return 0;
if (x == null || x.EntityLocomotive == null)
{
return 1;
}
if (y == null || y.EntityLocomotive == null)
{
return -1;
}
if (ToHex(x.EntityLocomotive.BodyColor) != ToHex(y.EntityLocomotive.BodyColor))
{
return String.Compare(ToHex(x.EntityLocomotive.BodyColor), ToHex(y.EntityLocomotive.BodyColor),
StringComparison.Ordinal);
}
var speedCompare = x.EntityLocomotive.Speed.CompareTo(y.EntityLocomotive.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityLocomotive.Weight.CompareTo(y.EntityLocomotive.Weight);
}
private static String ToHex(Color c) => $"#{c.R:X2}{c.G:X2}{c.B:X2}";
}
}

View File

@ -0,0 +1,36 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectElectricLocomotive.Drawnings;
/// <summary>
/// Сравнение по типу, скорости, весу
/// </summary>
public class DrawningLocomotiveCompareByType : IComparer<DrawningLocomotive?>
{
public int Compare(DrawningLocomotive? x, DrawningLocomotive? y)
{
if (x == null || x.EntityLocomotive == null)
{
return -1;
}
if (y == null || y.EntityLocomotive == null)
{
return 1;
}
if (x.GetType().Name != y.GetType().Name)
{
return x.GetType().Name.CompareTo(y.GetType().Name);
}
var speedCompare = x.EntityLocomotive.Speed.CompareTo(y.EntityLocomotive.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityLocomotive.Weight.CompareTo(y.EntityLocomotive.Weight);
}
}

View File

@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectElectricLocomotive.Exceptions
{
public class CollectionDuplicateException : Exception
{
public CollectionDuplicateException(object obj) : base("Объект " + obj + " не является уникальным") { }
public CollectionDuplicateException() : base() { }
public CollectionDuplicateException(string message) : base(message) { }
public CollectionDuplicateException(string message, Exception exception) :
base(message, exception)
{ }
protected CollectionDuplicateException(SerializationInfo info, StreamingContext
contex) : base(info, contex) { }
}
}

View File

@ -0,0 +1,21 @@
using ProjectElectricLocomotive.CollectionGenericObjects;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectElectricLocomotive.Exceptions
{
[Serializable]
public class CollectionExistsException : Exception
{
public CollectionExistsException() : base() { }
public CollectionExistsException(CollectionInfo collectionInfo) : base("Коллекция " + collectionInfo + " уже создана") { }
public CollectionExistsException(string name, Exception exception) : base("Коллекция " + name + " уже создана", exception)
{ }
protected CollectionExistsException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}
}

View File

@ -0,0 +1,20 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectElectricLocomotive.Exceptions
{
public class CollectionNoInfoException : Exception
{
public CollectionNoInfoException() : base() { }
public CollectionNoInfoException(string message) : base(message) { }
public CollectionNoInfoException(string message, Exception exception) :
base(message, exception)
{ }
protected CollectionNoInfoException(SerializationInfo info, StreamingContext
contex) : base(info, contex) { }
}
}

View File

@ -0,0 +1,22 @@
using ProjectElectricLocomotive.CollectionGenericObjects;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectElectricLocomotive.Exceptions
{
[Serializable]
public class CollectionNoTypeException : Exception
{
public CollectionNoTypeException() : base() { }
public CollectionNoTypeException(string message) : base(message) { }
public CollectionNoTypeException(string message, Exception exception) :
base(message, exception)
{ }
protected CollectionNoTypeException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}
}

View File

@ -0,0 +1,20 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectElectricLocomotive.Exceptions
{
public class DrawningEqutablesException : Exception
{
public DrawningEqutablesException() : base("Оба объекта прорисовки одинаковые") { }
public DrawningEqutablesException(string message) : base(message) { }
public DrawningEqutablesException(string message, Exception exception) :
base(message, exception)
{ }
protected DrawningEqutablesException(SerializationInfo info, StreamingContext
contex) : base(info, contex) { }
}
}

View File

@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectElectricLocomotive.Exceptions
{
public class EmptyFileExeption : Exception
{
public EmptyFileExeption(string name) : base("Файл" + name + "пустой ") { }
public EmptyFileExeption() : base("В хранилище отсутствуют коллекции для сохранения") { }
public EmptyFileExeption(string name, string message) : base(message) { }
public EmptyFileExeption(string name, string message, Exception exception) :
base(message, exception)
{ }
protected EmptyFileExeption(SerializationInfo info, StreamingContext
contex) : base(info, contex) { }
}
}

View File

@ -52,6 +52,8 @@
LoadToolStripMenuItem = new ToolStripMenuItem();
openFileDialog = new OpenFileDialog();
saveFileDialog = new SaveFileDialog();
buttonSortByColor = new Button();
buttonSortByType = new Button();
groupBoxTools.SuspendLayout();
panelCompanyTools.SuspendLayout();
panelStorage.SuspendLayout();
@ -76,7 +78,9 @@
//
// panelCompanyTools
//
panelCompanyTools.Controls.Add(buttonSortByColor);
panelCompanyTools.Controls.Add(buttonAddLocomotive);
panelCompanyTools.Controls.Add(buttonSortByType);
panelCompanyTools.Controls.Add(maskedTextBox);
panelCompanyTools.Controls.Add(buttonDelLocomotive);
panelCompanyTools.Controls.Add(buttonRefresh);
@ -99,7 +103,7 @@
//
// maskedTextBox
//
maskedTextBox.Location = new Point(12, 146);
maskedTextBox.Location = new Point(12, 82);
maskedTextBox.Mask = "00";
maskedTextBox.Name = "maskedTextBox";
maskedTextBox.Size = new Size(193, 31);
@ -108,7 +112,7 @@
//
// buttonDelLocomotive
//
buttonDelLocomotive.Location = new Point(12, 183);
buttonDelLocomotive.Location = new Point(12, 119);
buttonDelLocomotive.Name = "buttonDelLocomotive";
buttonDelLocomotive.Size = new Size(193, 63);
buttonDelLocomotive.TabIndex = 5;
@ -118,7 +122,7 @@
//
// buttonRefresh
//
buttonRefresh.Location = new Point(12, 297);
buttonRefresh.Location = new Point(12, 233);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(193, 39);
buttonRefresh.TabIndex = 7;
@ -128,7 +132,7 @@
//
// buttonGoToCheck
//
buttonGoToCheck.Location = new Point(12, 252);
buttonGoToCheck.Location = new Point(12, 188);
buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(193, 39);
buttonGoToCheck.TabIndex = 6;
@ -288,6 +292,26 @@
//
saveFileDialog.Filter = "txt file | *.txt";
//
// buttonSortByColor
//
buttonSortByColor.Location = new Point(12, 323);
buttonSortByColor.Name = "buttonSortByColor";
buttonSortByColor.Size = new Size(193, 37);
buttonSortByColor.TabIndex = 9;
buttonSortByColor.Text = "Сортировка по цвет";
buttonSortByColor.UseVisualStyleBackColor = true;
buttonSortByColor.Click += buttonSortByColor_Click;
//
// buttonSortByType
//
buttonSortByType.Location = new Point(12, 278);
buttonSortByType.Name = "buttonSortByType";
buttonSortByType.Size = new Size(193, 39);
buttonSortByType.TabIndex = 8;
buttonSortByType.Text = "Сортировка по типу";
buttonSortByType.UseVisualStyleBackColor = true;
buttonSortByType.Click += buttonSortByType_Click;
//
// FormLocomotiveCollection
//
AutoScaleDimensions = new SizeF(10F, 25F);
@ -338,5 +362,7 @@
private ToolStripMenuItem LoadToolStripMenuItem;
private OpenFileDialog openFileDialog;
private SaveFileDialog saveFileDialog;
private Button buttonSortByColor;
private Button buttonSortByType;
}
}

View File

@ -31,7 +31,7 @@ public partial class FormLocomotiveCollection : Form
/// <summary>
/// Логер
/// </summary>
private readonly ILogger _logger;
private readonly ILogger _logger;
/// <summary>
/// Компания
@ -96,12 +96,11 @@ public partial class FormLocomotiveCollection : Form
_logger.LogInformation("Добавлен объект: " + locomotive.GetDataForSave());
}
}
catch (ObjectNotFoundException) { }
catch (CollectionOverflowException ex)
catch (Exception ex)
{
//MessageBox.Show("Не удалось добавить объект");
MessageBox.Show(ex.Message);
_logger.LogError("Ошибка: {Message}", ex.Message);
MessageBox.Show($"Объект не добавлен: {ex.Message}", "Результат", MessageBoxButtons.OK,
MessageBoxIcon.Error);
_logger.LogError($"Ошибка: {ex.Message}", ex.Message);
}
}
@ -195,14 +194,13 @@ public partial class FormLocomotiveCollection : Form
/// </summary>
private void RerfreshListBoxItems()
{
listBoxCollection.Items.Clear();
for (int i = 0; i < _storageCollection.Keys?.Count; ++i)
{
string? colName = _storageCollection.Keys?[i];
if (!string.IsNullOrEmpty(colName))
CollectionInfo? col = _storageCollection.Keys?[i];
if (!col!.IsEmpty())
{
listBoxCollection.Items.Add(colName);
listBoxCollection.Items.Add(col);
}
}
}
@ -219,18 +217,21 @@ public partial class FormLocomotiveCollection : Form
MessageBox.Show("Коллекция не выбрана");
return;
}
ICollectionGenericObjects<DrawningLocomotive>? collection =
_storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty];
_storageCollection[
CollectionInfo.GetCollectionInfo(listBoxCollection.SelectedItem.ToString()!) ??
new CollectionInfo("", CollectionType.None, "Description")];
if (collection == null)
{
MessageBox.Show("Коллекция не проинициализирована");
return;
}
switch (comboBoxSelectorCompany.Text)
{
case "Депо":
_company = new LocomotiveDepo(pictureBox.Width,
pictureBox.Height, collection);
_company = new LocomotiveDepo(pictureBox.Width, pictureBox.Height, collection);
break;
}
panelCompanyTools.Enabled = true;
@ -246,25 +247,23 @@ public partial class FormLocomotiveCollection : Form
/// <param name="e"></param>
private void buttonCollectionDel_Click(object sender, EventArgs e)
{
// TODO прописать логику удаления элемента из коллекции
// нужно убедиться, что есть выбранная коллекция
// спросить у пользователя через MessageBox, что он подтверждает, что хочет удалить запись
// удалить и обновить ListBox
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
{
MessageBox.Show("Коллекция не выбрана");
return;
}
try
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
return;
}
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
RerfreshListBoxItems();
_logger.LogInformation("Коллекция: " + listBoxCollection.SelectedItem.ToString() + " удалена");
}
catch (Exception ex)
{
_logger.LogError("Ошибка: {Message}", ex.Message);
return;
}
CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(listBoxCollection.SelectedItem.ToString()!);
_storageCollection.DelCollection(collectionInfo!);
_logger.LogInformation("Коллекция удалена");
RerfreshListBoxItems();
}
/// <summary>
@ -276,27 +275,29 @@ public partial class FormLocomotiveCollection : Form
{
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked))
{
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBox.Show("Не все данные заполнены", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
CollectionType collectionType = CollectionType.None;
if (radioButtonMassive.Checked)
{
collectionType = CollectionType.Massive;
}
else if (radioButtonList.Checked)
{
collectionType = CollectionType.List;
}
try
{
CollectionType collectionType = CollectionType.None;
if (radioButtonMassive.Checked)
{
collectionType = CollectionType.Massive;
}
else if (radioButtonList.Checked)
{
collectionType = CollectionType.List;
}
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
_storageCollection.AddCollection(new CollectionInfo(textBoxCollectionName.Text, collectionType, ""));
_logger.LogInformation("Добавление коллекции");
RerfreshListBoxItems();
_logger.LogInformation("Коллекция добавлена " + textBoxCollectionName.Text);
}
catch (Exception ex)
{
_logger.LogError("Ошибка: {Message}", ex.Message);
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError($"Ошибка: {ex.Message}", ex.Message);
}
}
@ -352,4 +353,39 @@ public partial class FormLocomotiveCollection : Form
}
}
}
/// <summary>
/// Сортировка по цвету
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonSortByColor_Click(object sender, EventArgs e)
{
CompareLocomotives(new DrawningLocomotiveCompareByColor());
}
/// <summary>
/// Сортировка по типу
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonSortByType_Click(object sender, EventArgs e)
{
CompareLocomotives(new DrawningLocomotiveCompareByType());
}
/// <summary>
/// Сортировка по сравнителю
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
private void CompareLocomotives(IComparer<DrawningLocomotive?> comparer)
{
if (_company == null)
{
return;
}
_company.Sort(comparer);
pictureBox.Image = _company.Show();
}
}