Лабораторная работа №8

This commit is contained in:
Anitonchik 2024-05-13 22:43:42 +04:00
parent 1735062212
commit 3ecffd4d54
12 changed files with 394 additions and 54 deletions

View File

@ -38,6 +38,7 @@ public abstract class AbstractCompany
/// </summary> /// </summary>
private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight); private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight);
/// <summary> /// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
@ -60,7 +61,7 @@ public abstract class AbstractCompany
/// <returns></returns> /// <returns></returns>
public static int operator +(AbstractCompany company, DrawningTruck truck) public static int operator +(AbstractCompany company, DrawningTruck truck)
{ {
return company._collection.Insert(truck); return company._collection.Insert(truck, new DrawiningTruckEqutables());
} }
/// <summary> /// <summary>
@ -105,6 +106,13 @@ public abstract class AbstractCompany
} }
return bitmap; return bitmap;
} }
/// <summary>
/// Сортировка
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
public void Sort(IComparer<DrawningTruck?> comparer) => _collection?.CollectionSort(comparer);
/// <summary> /// <summary>
/// Вывод заднего фона /// Вывод заднего фона
/// </summary> /// </summary>
@ -114,4 +122,6 @@ public abstract class AbstractCompany
/// Расстановка объектов /// Расстановка объектов
/// </summary> /// </summary>
protected abstract void SetObjectsPosition(); protected abstract void SetObjectsPosition();
} }

View File

@ -0,0 +1,71 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectDumpTruck.CollectionGenericObjects;
public class 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();
}
}

View File

@ -1,4 +1,6 @@
using System; using ProjectDumpTruck.Drawnings;
using System;
using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
@ -27,14 +29,14 @@ where T : class
/// </summary> /// </summary>
/// <param name="obj">Добавляемый объект</param> /// <param name="obj">Добавляемый объект</param>
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns> /// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
int Insert(T obj); int Insert(T obj, IEqualityComparer<T?>? comparer = null);
/// <summary> /// <summary>
/// Добавление объекта в коллекцию на конкретную позицию /// Добавление объекта в коллекцию на конкретную позицию
/// </summary> /// </summary>
/// /// <param name="obj">Добавляемый объект</param> /// /// <param name="obj">Добавляемый объект</param>
/// <param name="position">Позиция</param> /// <param name="position">Позиция</param>
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns> /// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
int Insert(T obj, int position); int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null);
/// <summary> /// <summary>
/// Удаление объекта из коллекции с конкретной позиции /// Удаление объекта из коллекции с конкретной позиции
/// </summary> /// </summary>
@ -57,6 +59,10 @@ where T : class
/// </summary> /// </summary>
/// <returns>Поэлементый вывод элементов коллекции</returns> /// <returns>Поэлементый вывод элементов коллекции</returns>
IEnumerable<T?> GetItems(); IEnumerable<T?> GetItems();
/// <summary>
/// Сортировка коллекции
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
void CollectionSort(IComparer<T?> comparer);
} }

View File

@ -1,4 +1,5 @@
using ProjectDumpTruck.Exceptions; using ProjectDumpTruck.Drawnings;
using ProjectDumpTruck.Exceptions;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
@ -27,7 +28,7 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
{ {
get get
{ {
return MaxCount; return _maxCount;
} }
set set
{ {
@ -56,8 +57,15 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
return _collection[position]; return _collection[position];
} }
public int Insert(T obj) public int Insert(T obj, IEqualityComparer<T?>? comparer = null)
{ {
if (comparer != null)
{
if (_collection.Contains(obj, comparer))
{
throw new ObjectsEqualException();
}
}
if (_collection.Count >= _maxCount) if (_collection.Count >= _maxCount)
{ {
throw new CollectionOverflowException(MaxCount); throw new CollectionOverflowException(MaxCount);
@ -66,8 +74,15 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
return _collection.Count; return _collection.Count;
} }
public int Insert(T obj, int position) public int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
{ {
if (comparer != null)
{
if (_collection.Contains(obj, comparer))
{
throw new ObjectsEqualException(position);
}
}
if (position < 0 || position > _maxCount) if (position < 0 || position > _maxCount)
{ {
throw new PositionOutOfCollectionException(position); throw new PositionOutOfCollectionException(position);
@ -99,5 +114,10 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
yield return _collection[i]; yield return _collection[i];
} }
} }
public void CollectionSort(IComparer<T?> comparer)
{
_collection.Sort(comparer);
}
} }

View File

@ -63,25 +63,45 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
} }
return _collection[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 < MaxCount; ++i) for (int i = 0; i < MaxCount; ++i)
{ {
if ((comparer as IEqualityComparer<DrawningTruck>).Equals(obj as DrawningTruck, _collection[i] as DrawningTruck))
{
throw new ObjectsEqualException(i);
}
if (_collection[i] == null) if (_collection[i] == null)
{ {
_collection[i] = obj; _collection[i] = obj;
return i; return i;
} }
} }
}
throw new CollectionOverflowException(Count); throw new CollectionOverflowException(Count);
} }
public int Insert(T obj, int position)
public int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
{ {
if (position < 0 || position >= MaxCount) if (position < 0 || position >= MaxCount)
{ {
throw new PositionOutOfCollectionException(Count); throw new PositionOutOfCollectionException(Count);
} }
if (comparer != null)
{
for (int i = 0; i < position; i++)
{
if (_collection[i] != null)
{
if ((comparer as IEqualityComparer<DrawningTruck>).Equals(obj as DrawningTruck, _collection[i] as DrawningTruck))
{
throw new ObjectsEqualException(i);
}
}
}
}
if (_collection[position] == null) if (_collection[position] == null)
{ {
_collection[position] = obj; _collection[position] = obj;
@ -127,5 +147,10 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
yield return _collection[i]; yield return _collection[i];
} }
} }
public void CollectionSort(IComparer<T?> comparer)
{
Array.Sort(_collection, comparer);
}
} }

View File

@ -18,11 +18,11 @@ public class StorageCollection<T>
/// <summary> /// <summary>
/// Словарь (хранилище) с коллекциями /// Словарь (хранилище) с коллекциями
/// </summary> /// </summary>
readonly Dictionary<string, ICollectionGenericObjects<T>> _storages; readonly Dictionary<CollectionInfo, ICollectionGenericObjects<T>> _storages;
/// <summary> /// <summary>
/// Возвращение списка названий коллекций /// Возвращение списка названий коллекций
/// </summary> /// </summary>
public List<string> Keys => _storages.Keys.ToList(); public List<CollectionInfo> Keys => _storages.Keys.ToList();
/// <summary> /// <summary>
/// Ключевое слово, с которого должен начинаться файл /// Ключевое слово, с которого должен начинаться файл
@ -42,7 +42,7 @@ public class StorageCollection<T>
/// </summary> /// </summary>
public StorageCollection() public StorageCollection()
{ {
_storages = new Dictionary<string, ICollectionGenericObjects<T>>(); _storages = new Dictionary<CollectionInfo, ICollectionGenericObjects<T>>();
} }
/// <summary> /// <summary>
@ -52,7 +52,8 @@ public class StorageCollection<T>
/// <param name="collectionType">тип коллекции</param> /// <param name="collectionType">тип коллекции</param>
public void AddCollection(string name, CollectionType collectionType) public void AddCollection(string name, CollectionType collectionType)
{ {
if (_storages.ContainsKey(name)) CollectionInfo info = new CollectionInfo(name, collectionType, string.Empty);
if (_storages.ContainsKey(info))
{ {
return; return;
} }
@ -61,10 +62,10 @@ public class StorageCollection<T>
case CollectionType.None: case CollectionType.None:
return; return;
case CollectionType.Massive: case CollectionType.Massive:
_storages.Add(name, new MassiveGenericObjects<T>()); _storages.Add(info, new MassiveGenericObjects<T>());
break; break;
case CollectionType.List: case CollectionType.List:
_storages.Add(name, new ListGenericObjects<T>()); _storages.Add(info, new ListGenericObjects<T>());
break; break;
} }
} }
@ -75,9 +76,10 @@ public class StorageCollection<T>
/// <param name="name">Название коллекции</param> /// <param name="name">Название коллекции</param>
public void DelCollection(string name) public void DelCollection(string name)
{ {
if (_storages.ContainsKey(name)) CollectionInfo info = new CollectionInfo(name, CollectionType.None, string.Empty);
if (_storages.ContainsKey(info))
{ {
_storages.Remove(name); _storages.Remove(info);
} }
} }
@ -91,9 +93,10 @@ public class StorageCollection<T>
{ {
get get
{ {
if (_storages.ContainsKey(name)) CollectionInfo info = new CollectionInfo(name, CollectionType.None, string.Empty);
if (_storages.ContainsKey(info))
{ {
return _storages[name]; return _storages[info];
} }
return null; return null;
} }
@ -121,16 +124,14 @@ public class StorageCollection<T>
wr.Write(_collectionKey); wr.Write(_collectionKey);
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages) foreach (KeyValuePair<CollectionInfo, ICollectionGenericObjects<T>> value in _storages)
{ {
wr.Write(Environment.NewLine); wr.Write(Environment.NewLine);
if (value.Value.Count == 0) if (value.Value.Count == 0)
{ {
continue; continue;
} }
wr.Write(value.Key); wr.Write(value.Key.ToString());
wr.Write(_separatorForKeyValue);
wr.Write(value.Value.GetCollectionType);
wr.Write(_separatorForKeyValue); wr.Write(_separatorForKeyValue);
wr.Write(value.Value.MaxCount); wr.Write(value.Value.MaxCount);
wr.Write(_separatorForKeyValue); wr.Write(_separatorForKeyValue);
@ -177,18 +178,21 @@ public class StorageCollection<T>
while ((strs = rd.ReadLine()) != null) while ((strs = rd.ReadLine()) != null)
{ {
string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 4) if (record.Length != 3)
{ {
continue; continue;
} }
CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]); CollectionInfo? col_info = CollectionInfo.GetCollectionInfo(record[0]) ??
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType); throw new Exception("Не удалось определить информацию коллекции: " + record[0]); ;
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(col_info.CollectionType) ??
throw new Exception("Не удалось создать коллекцию");
if (collection == null) if (collection == null)
{ {
throw new Exception("Не удалось создать коллекции"); throw new Exception("Не удалось создать коллекции");
} }
collection.MaxCount = Convert.ToInt32(record[2]); collection.MaxCount = Convert.ToInt32(record[1]);
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set) foreach (string elem in set)
{ {
if (elem?.CreateDrawningTruck() is T truck) if (elem?.CreateDrawningTruck() is T truck)
@ -207,7 +211,7 @@ public class StorageCollection<T>
} }
} }
_storages.Add(record[0], collection); _storages.Add(col_info, collection);
} }
} }

View File

@ -0,0 +1,63 @@
using ProjectDumpTruck.Entities;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectDumpTruck.Drawnings;
public class DrawiningTruckEqutables : IEqualityComparer<DrawningTruck?>
{
public bool Equals(DrawningTruck? x, DrawningTruck? y)
{
if (x == null || x.EntityTruck == null)
{
return false;
}
if (y == null || y.EntityTruck == null)
{
return false;
}
if (x.GetType().Name != y.GetType().Name)
{
return false;
}
if (x.EntityTruck.Speed != y.EntityTruck.Speed)
{
return false;
}
if (x.EntityTruck.Weight != y.EntityTruck.Weight)
{
return false;
}
if (x.EntityTruck.BodyColor != y.EntityTruck.BodyColor)
{
return false;
}
if (x is DrawningDumpTruck && y is DrawningDumpTruck)
{
EntityDumpTruck dump_truck_x = (EntityDumpTruck)x.EntityTruck;
EntityDumpTruck dump_truck_y = (EntityDumpTruck)y.EntityTruck;
if (dump_truck_x.Body != dump_truck_y.Body)
{
return false;
}
if (dump_truck_x.Tent != dump_truck_y.Tent)
{
return false;
}
if (dump_truck_x.AdditionalColor != dump_truck_y.AdditionalColor)
{
return false;
}
}
return true;
}
public int GetHashCode([DisallowNull] DrawningTruck? obj)
{
throw new NotImplementedException();
}
}

View File

@ -0,0 +1,35 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectDumpTruck.Drawnings;
public class DrawningTruckCompareByColor : IComparer<DrawningTruck?>
{
public int Compare(DrawningTruck? x, DrawningTruck? y)
{
if (x == null || x.EntityTruck == null)
{
return 1;
}
if (y == null || y.EntityTruck == null)
{
return -1;
}
var bodycolorCompare = x.EntityTruck.BodyColor.Name.CompareTo(y.EntityTruck.BodyColor.Name);
if (bodycolorCompare != 0)
{
return bodycolorCompare;
}
var speedCompare = x.EntityTruck.Speed.CompareTo(y.EntityTruck.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityTruck.Weight.CompareTo(y.EntityTruck.Weight);
}
}

View File

@ -0,0 +1,32 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectDumpTruck.Drawnings;
public class DrawningTruckCompareByType : IComparer<DrawningTruck?>
{
public int Compare(DrawningTruck? x, DrawningTruck? y)
{
if (x == null || x.EntityTruck == null)
{
return -1;
}
if (y == null || y.EntityTruck == null)
{
return 1;
}
if (x.GetType().Name != y.GetType().Name)
{
return x.GetType().Name.CompareTo(y.GetType().Name);
}
var speedCompare = x.EntityTruck.Speed.CompareTo(y.EntityTruck.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityTruck.Weight.CompareTo(y.EntityTruck.Weight);
}
}

View File

@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectDumpTruck.Exceptions;
public class ObjectsEqualException : ApplicationException
{
public ObjectsEqualException(int i) : base("В коллекции находится такой же элемент на позиции " + i) { }
public ObjectsEqualException() : base( "В коллекции находится такой же элемент") { }
public ObjectsEqualException(string message) : base(message) { }
public ObjectsEqualException(string message, Exception exception) : base(message, exception) { }
protected ObjectsEqualException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}

View File

@ -52,6 +52,8 @@
loadToolStripMenuItem = new ToolStripMenuItem(); loadToolStripMenuItem = new ToolStripMenuItem();
saveFileDialog = new SaveFileDialog(); saveFileDialog = new SaveFileDialog();
openFileDialog = new OpenFileDialog(); openFileDialog = new OpenFileDialog();
buttonSortByColor = new Button();
buttonSortByType = new Button();
groupBoxTools.SuspendLayout(); groupBoxTools.SuspendLayout();
panelCompanyTools.SuspendLayout(); panelCompanyTools.SuspendLayout();
panelStorage.SuspendLayout(); panelStorage.SuspendLayout();
@ -68,22 +70,24 @@
groupBoxTools.Dock = DockStyle.Right; groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(832, 28); groupBoxTools.Location = new Point(832, 28);
groupBoxTools.Name = "groupBoxTools"; groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(250, 799); groupBoxTools.Size = new Size(250, 925);
groupBoxTools.TabIndex = 0; groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false; groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты"; groupBoxTools.Text = "Инструменты";
// //
// panelCompanyTools // panelCompanyTools
// //
panelCompanyTools.Controls.Add(buttonSortByColor);
panelCompanyTools.Controls.Add(buttonSortByType);
panelCompanyTools.Controls.Add(buttonAddTruck); panelCompanyTools.Controls.Add(buttonAddTruck);
panelCompanyTools.Controls.Add(buttonRefresh); panelCompanyTools.Controls.Add(buttonRefresh);
panelCompanyTools.Controls.Add(maskedTextBoxPosition); panelCompanyTools.Controls.Add(maskedTextBoxPosition);
panelCompanyTools.Controls.Add(buttonGoToChek); panelCompanyTools.Controls.Add(buttonGoToChek);
panelCompanyTools.Controls.Add(buttonRemoveTruck); panelCompanyTools.Controls.Add(buttonRemoveTruck);
panelCompanyTools.Dock = DockStyle.Bottom; panelCompanyTools.Dock = DockStyle.Bottom;
panelCompanyTools.Location = new Point(3, 464); panelCompanyTools.Location = new Point(3, 479);
panelCompanyTools.Name = "panelCompanyTools"; panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(244, 332); panelCompanyTools.Size = new Size(244, 443);
panelCompanyTools.TabIndex = 4; panelCompanyTools.TabIndex = 4;
// //
// buttonAddTruck // buttonAddTruck
@ -245,7 +249,7 @@
pictureBox.Dock = DockStyle.Fill; pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 28); pictureBox.Location = new Point(0, 28);
pictureBox.Name = "pictureBox"; pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(832, 799); pictureBox.Size = new Size(832, 925);
pictureBox.TabIndex = 3; pictureBox.TabIndex = 3;
pictureBox.TabStop = false; pictureBox.TabStop = false;
// //
@ -291,11 +295,31 @@
openFileDialog.FileName = "openFileDialog1"; openFileDialog.FileName = "openFileDialog1";
openFileDialog.Filter = "txt file | *.txt"; openFileDialog.Filter = "txt file | *.txt";
// //
// buttonSortByColor
//
buttonSortByColor.Location = new Point(15, 371);
buttonSortByColor.Name = "buttonSortByColor";
buttonSortByColor.Size = new Size(220, 57);
buttonSortByColor.TabIndex = 8;
buttonSortByColor.Text = "Сортировка по цвету";
buttonSortByColor.UseVisualStyleBackColor = true;
buttonSortByColor.Click += buttonSortByColor_Click;
//
// buttonSortByType
//
buttonSortByType.Location = new Point(15, 308);
buttonSortByType.Name = "buttonSortByType";
buttonSortByType.Size = new Size(220, 57);
buttonSortByType.TabIndex = 7;
buttonSortByType.Text = "Сортировка по типу";
buttonSortByType.UseVisualStyleBackColor = true;
buttonSortByType.Click += buttonSortByType_Click;
//
// FormTruckCollection // FormTruckCollection
// //
AutoScaleDimensions = new SizeF(8F, 20F); AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font; AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1082, 827); ClientSize = new Size(1082, 953);
Controls.Add(pictureBox); Controls.Add(pictureBox);
Controls.Add(groupBoxTools); Controls.Add(groupBoxTools);
Controls.Add(menuStrip); Controls.Add(menuStrip);
@ -340,5 +364,7 @@
private ToolStripMenuItem loadToolStripMenuItem; private ToolStripMenuItem loadToolStripMenuItem;
private SaveFileDialog saveFileDialog; private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog; private OpenFileDialog openFileDialog;
private Button buttonSortByColor;
private Button buttonSortByType;
} }
} }

View File

@ -82,11 +82,16 @@ public partial class FormTruckCollection : Form
_logger.LogInformation("Объект добавлен"); _logger.LogInformation("Объект добавлен");
} }
} }
catch (Exception ex) catch (ObjectNotFoundException) { }
catch (CollectionOverflowException ex)
{ {
MessageBox.Show("Коллекция переполнена");
MessageBox.Show("Не удалось добавить объект"); _logger.LogError("Ошибка: {Message}", ex.Message);
_logger.LogWarning($"Ошибка: {ex.Message}"); }
catch (ObjectsEqualException ex)
{
MessageBox.Show("Такой объект уже существует в коллекции");
_logger.LogError("Ошибка: {Message}", ex.Message);
} }
@ -118,7 +123,8 @@ public partial class FormTruckCollection : Form
_logger.LogInformation("Объект удален"); _logger.LogInformation("Объект удален");
} }
} }
catch (Exception ex) { catch (Exception ex)
{
MessageBox.Show("Не удалось удалить объект"); MessageBox.Show("Не удалось удалить объект");
_logger.LogError("Ошибка: {Message}", ex.Message); _logger.LogError("Ошибка: {Message}", ex.Message);
} }
@ -205,7 +211,7 @@ public partial class FormTruckCollection : Form
listBoxCollection.Items.Clear(); listBoxCollection.Items.Clear();
for (int i = 0; i < _storageCollection.Keys?.Count; ++i) for (int i = 0; i < _storageCollection.Keys?.Count; ++i)
{ {
string? colName = _storageCollection.Keys?[i]; string? colName = _storageCollection.Keys?[i].Name;
if (!string.IsNullOrEmpty(colName)) if (!string.IsNullOrEmpty(colName))
{ {
listBoxCollection.Items.Add(colName); listBoxCollection.Items.Add(colName);
@ -299,5 +305,30 @@ public partial class FormTruckCollection : Form
} }
} }
} }
private void buttonSortByType_Click(object sender, EventArgs e)
{
CompareTrucks(new DrawningTruckCompareByType());
}
private void buttonSortByColor_Click(object sender, EventArgs e)
{
CompareTrucks(new DrawningTruckCompareByColor());
}
/// <summary>
/// Сортировка по сравнителю
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
private void CompareTrucks(IComparer<DrawningTruck?> comparer)
{
if (_company == null)
{
return;
}
_company.Sort(comparer);
pictureBox.Image = _company.Show();
}
} }