From 60ed1b5dddfff8ce2f6c8fa6ddaeb133ddaebbca Mon Sep 17 00:00:00 2001 From: aaahsap Date: Tue, 14 May 2024 01:34:15 +0400 Subject: [PATCH] =?UTF-8?q?=D0=9B=D0=B0=D0=B1=D0=B0=D1=80=D0=B0=D1=82?= =?UTF-8?q?=D0=BE=D1=80=D0=BD=D0=B0=D1=8F=20=D1=80=D0=B0=D0=B1=D0=BE=D1=82?= =?UTF-8?q?=D0=B0=208?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../AbstractCompany.cs | 8 +- .../CollectionInfo.cs | 82 +++++++++++++++++++ .../ICollectionGenericObjects.cs | 12 ++- .../ListGenericObjects.cs | 24 +++++- .../MassiveGenericObjects.cs | 52 ++++++++---- .../StorageCollection.cs | 45 +++++----- Lab1/Lab1/Drawnings/DrawningCarEqutables.cs | 73 +++++++++++++++++ Lab1/Lab1/Drawnings/DrawningCompareByColor.cs | 37 +++++++++ Lab1/Lab1/Drawnings/DrawningCompareByType.cs | 38 +++++++++ .../Exceptions/ObjectNotUniqueException.cs | 21 +++++ Lab1/Lab1/FormTruckCollection.Designer.cs | 38 ++++++++- Lab1/Lab1/FormTruckCollection.cs | 29 ++++++- 12 files changed, 411 insertions(+), 48 deletions(-) create mode 100644 Lab1/Lab1/CollectionGenericObjects/CollectionInfo.cs create mode 100644 Lab1/Lab1/Drawnings/DrawningCarEqutables.cs create mode 100644 Lab1/Lab1/Drawnings/DrawningCompareByColor.cs create mode 100644 Lab1/Lab1/Drawnings/DrawningCompareByType.cs create mode 100644 Lab1/Lab1/Exceptions/ObjectNotUniqueException.cs diff --git a/Lab1/Lab1/CollectionGenericObjects/AbstractCompany.cs b/Lab1/Lab1/CollectionGenericObjects/AbstractCompany.cs index e729ac3..404447e 100644 --- a/Lab1/Lab1/CollectionGenericObjects/AbstractCompany.cs +++ b/Lab1/Lab1/CollectionGenericObjects/AbstractCompany.cs @@ -60,7 +60,7 @@ public abstract class AbstractCompany /// public static int operator +(AbstractCompany company, DrawningTruck truck) { - return company._collection.Insert(truck); + return company._collection.Insert(truck, new DrawningCarEqutables()); } /// @@ -118,4 +118,10 @@ public abstract class AbstractCompany /// Расстановка объектов /// protected abstract void SetObjectsPosition(); + + /// + /// Сортировка + /// + /// Сравнитель объектов + public void Sort(IComparer comparer) => _collection?.CollectionSort(comparer); } diff --git a/Lab1/Lab1/CollectionGenericObjects/CollectionInfo.cs b/Lab1/Lab1/CollectionGenericObjects/CollectionInfo.cs new file mode 100644 index 0000000..a7ec59e --- /dev/null +++ b/Lab1/Lab1/CollectionGenericObjects/CollectionInfo.cs @@ -0,0 +1,82 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Lab1.CollectionGenericObjects; + +/// +/// Класс, хранящиий информацию по коллекции +/// +public class CollectionInfo : IEquatable +{ + /// + /// Название + /// + public string Name { get; private set; } + + /// + /// Тип + /// + public CollectionType CollectionType { get; private set; } + + /// + /// Описание + /// + public string Description { get; private set; } + + /// + /// Разделитель для записи информации по объекту в файл + /// + private static readonly string _separator = "-"; + + /// + /// Конструктор + /// + /// Название + /// Тип + /// Описание + public CollectionInfo(string name, CollectionType collectionType, string description) + { + Name = name; + CollectionType = collectionType; + Description = description; + } + + /// + /// Создание объекта из строки + /// + /// Строка + /// Объект или null + 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(); + } +} \ No newline at end of file diff --git a/Lab1/Lab1/CollectionGenericObjects/ICollectionGenericObjects.cs b/Lab1/Lab1/CollectionGenericObjects/ICollectionGenericObjects.cs index 461b0d8..f00ccbd 100644 --- a/Lab1/Lab1/CollectionGenericObjects/ICollectionGenericObjects.cs +++ b/Lab1/Lab1/CollectionGenericObjects/ICollectionGenericObjects.cs @@ -23,16 +23,18 @@ public interface ICollectionGenericObjects /// Добавление объекта в коллекцию /// /// Добавляемый объект + /// /// Cравнение двух объектов /// true - вставка прошла удачно, false - вставка не удалась - int Insert(T obj); + int Insert(T obj, IEqualityComparer? comparer = null); /// /// Добавление объекта в коллекцию на конкретную позицию /// /// Добавляемый объект /// Позиция + /// /// Cравнение двух объектов /// true - вставка прошла удачно, false - вставка не удалась - int Insert(T obj, int position); + int Insert(T obj, int position, IEqualityComparer? comparer = null); /// /// Удаление объекта из коллекции с конкретной позиции @@ -58,4 +60,10 @@ public interface ICollectionGenericObjects /// /// Поэлементый вывод элементов коллекции IEnumerable GetItems(); + + /// + /// Сортировка коллекции + /// + /// Сравнитель объектов + void CollectionSort(IComparer comparer); } diff --git a/Lab1/Lab1/CollectionGenericObjects/ListGenericObjects.cs b/Lab1/Lab1/CollectionGenericObjects/ListGenericObjects.cs index 255ab4c..d170b38 100644 --- a/Lab1/Lab1/CollectionGenericObjects/ListGenericObjects.cs +++ b/Lab1/Lab1/CollectionGenericObjects/ListGenericObjects.cs @@ -41,20 +41,36 @@ where T : class return _collection[position]; } - public int Insert(T obj) + public int Insert(T obj, IEqualityComparer? comparer = null) { // TODO проверка, что не превышено максимальное количество элементов // TODO вставка в конец набора + if (comparer != null) + { + if (_collection.Contains(obj, comparer)) + { + throw new ObjectNotUniqueException(); + } + } + 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? comparer = null) { // TODO проверка, что не превышено максимальное количество элементов // TODO проверка позиции // TODO вставка по позиции + if (comparer != null) + { + if (_collection.Contains(obj, comparer)) + { + throw new ObjectNotUniqueException(); + } + } + if (Count == _maxCount) throw new CollectionOverflowException(Count); if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position); _collection.Insert(position, obj); @@ -78,5 +94,9 @@ where T : class yield return _collection[i]; } } + void ICollectionGenericObjects.CollectionSort(IComparer comparer) + { + _collection.Sort(comparer); + } } diff --git a/Lab1/Lab1/CollectionGenericObjects/MassiveGenericObjects.cs b/Lab1/Lab1/CollectionGenericObjects/MassiveGenericObjects.cs index 600e70d..580d0fe 100644 --- a/Lab1/Lab1/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/Lab1/Lab1/CollectionGenericObjects/MassiveGenericObjects.cs @@ -1,4 +1,5 @@ -using Lab1.Exceptions; +using Lab1.Drawnings; +using Lab1.Exceptions; using System; using System.Collections.Generic; using System.Linq; @@ -55,9 +56,17 @@ public class MassiveGenericObjects : ICollectionGenericObjects return _collection[position]; } - public int Insert(T obj) + public int Insert(T obj, IEqualityComparer? comparer = null) { - // TODO вставка в свободное место набора + if (comparer != null) + { + foreach (T? item in _collection) + { + if ((comparer as IEqualityComparer).Equals(obj as DrawningTruck, item as DrawningTruck)) + throw new ObjectNotUniqueException(); + } + } + int index = 0; while (index < _collection.Length) { @@ -66,45 +75,52 @@ public class MassiveGenericObjects : ICollectionGenericObjects _collection[index] = obj; return index; } - index++; } throw new CollectionOverflowException(Count); } - public int Insert(T obj, int position) + public int Insert(T obj, int position, IEqualityComparer? comparer = null) { // TODO проверка позиции // TODO проверка, что элемент массива по этой позиции пустой, если нет, то // ищется свободное место после этой позиции и идет вставка туда // если нет после, ищем до // TODO вставка - if (position >= _collection.Length || position < 0) - { throw new PositionOutOfCollectionException(position); } + if (comparer != null) + { + foreach (T? item in _collection) + { + if ((comparer as IEqualityComparer).Equals(obj as DrawningTruck, item as DrawningTruck)) + throw new ObjectNotUniqueException(); + } + } + if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position); if (_collection[position] == null) { _collection[position] = obj; return position; } - int index; - - for (index = position + 1; index < _collection.Length; ++index) + int index = position + 1; + while (index < _collection.Length) { if (_collection[index] == null) { - _collection[position] = obj; - return position; + _collection[index] = obj; + return index; } + ++index; } - - for (index = position - 1; index >= 0; --index) + index = position - 1; + while (index >= 0) { if (_collection[index] == null) { - _collection[position] = obj; - return position; + _collection[index] = obj; + return index; } + --index; } throw new CollectionOverflowException(Count); } @@ -129,4 +145,8 @@ public class MassiveGenericObjects : ICollectionGenericObjects yield return _collection[i]; } } + void ICollectionGenericObjects.CollectionSort(IComparer comparer) + { + Array.Sort(_collection, comparer); + } } diff --git a/Lab1/Lab1/CollectionGenericObjects/StorageCollection.cs b/Lab1/Lab1/CollectionGenericObjects/StorageCollection.cs index 23db620..3b6215f 100644 --- a/Lab1/Lab1/CollectionGenericObjects/StorageCollection.cs +++ b/Lab1/Lab1/CollectionGenericObjects/StorageCollection.cs @@ -17,12 +17,12 @@ public class StorageCollection /// /// Словарь (хранилище) с коллекциями /// - private Dictionary> _storages; + private Dictionary> _storages; /// /// Возвращение списка названий коллекций /// - public List Keys => _storages.Keys.ToList(); + public List Keys => _storages.Keys.ToList(); /// @@ -46,7 +46,7 @@ public class StorageCollection /// public StorageCollection() { - _storages = new Dictionary>(); + _storages = new Dictionary>(); } /// @@ -58,12 +58,13 @@ public class StorageCollection { // TODO проверка, что name не пустой и нет в словаре записи с таким ключом // TODO Прописать логику для добавления - if (_storages.ContainsKey(name)) return; + CollectionInfo collectionInfo = new CollectionInfo(name, collectionType, string.Empty); + if (_storages.ContainsKey(collectionInfo)) return; if (collectionType == CollectionType.None) return; else if (collectionType == CollectionType.Massive) - _storages[name] = new MassiveGenericObjects(); + _storages[collectionInfo] = new MassiveGenericObjects(); else if (collectionType == CollectionType.List) - _storages[name] = new ListGenericObjects(); + _storages[collectionInfo] = new ListGenericObjects(); } /// @@ -73,8 +74,9 @@ public class StorageCollection public void DelCollection(string name) { // TODO Прописать логику для удаления коллекции - if (_storages.ContainsKey(name)) - _storages.Remove(name); + CollectionInfo collectionInfo = new CollectionInfo(name, CollectionType.None, string.Empty); + if (_storages.ContainsKey(collectionInfo)) + _storages.Remove(collectionInfo); } /// @@ -86,8 +88,10 @@ public class StorageCollection { get { - if (name == null || !_storages.ContainsKey(name)) { return null; } - return _storages[name]; + CollectionInfo collectionInfo = new CollectionInfo(name, CollectionType.None, string.Empty); + if (_storages.ContainsKey(collectionInfo)) + return _storages[collectionInfo]; + return null; } } @@ -115,7 +119,7 @@ public class StorageCollection using StreamWriter streamWriter = new StreamWriter(fs); streamWriter.Write(_collectionKey); - foreach (KeyValuePair> value in _storages) + foreach (KeyValuePair> value in _storages) { streamWriter.Write(Environment.NewLine); @@ -126,8 +130,6 @@ public class StorageCollection streamWriter.Write(value.Key); streamWriter.Write(_separatorForKeyValue); - streamWriter.Write(value.Value.GetCollectionType); - streamWriter.Write(_separatorForKeyValue); streamWriter.Write(value.Value.MaxCount); streamWriter.Write(_separatorForKeyValue); @@ -186,24 +188,25 @@ public class StorageCollection string[] record = str.Split(_separatorForKeyValue); //разделяем строки на компоненты при помощи разделителя - if (record.Length != 4) + if (record.Length != 3) { continue; } //если длина записи не равна байту, читаем следующую строку - CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]); - ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType); + CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(record[0]) ?? + throw new Exception("Не удалось определить информацию коллекции: " + record[0]); + ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionInfo.CollectionType) ?? + throw new Exception("Не удалось создать коллекцию"); if (collection == null) { throw new Exception("Не удалось создать коллекцию"); } - //находим тип коллекции, создаем её экземпляр и если коллекция пустая, возвращаем false. - - 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) { if (elem?.CreateDrawningTruck() is T ship) @@ -224,7 +227,7 @@ public class StorageCollection //элементы из строки записи добавляем в коллекцию, проверяем, является ли каждый элемент объектом типа T, и, //если да, то добавляем его в коллекцию. Если операция вставки не удалась, возвращаем false - _storages.Add(record[0], collection); + _storages.Add(collectionInfo, collection); //Загруженную коллекцию добавляем в хранилище с ключом, извлеченным из записи. } } diff --git a/Lab1/Lab1/Drawnings/DrawningCarEqutables.cs b/Lab1/Lab1/Drawnings/DrawningCarEqutables.cs new file mode 100644 index 0000000..ab73d21 --- /dev/null +++ b/Lab1/Lab1/Drawnings/DrawningCarEqutables.cs @@ -0,0 +1,73 @@ +using Lab1.Entities; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Lab1.Drawnings; +/// +/// Реализация сравнения двух объектов класса-прорисовки +/// +public class DrawningCarEqutables : IEqualityComparer +{ + 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 DrawningRoadTrain && y is DrawningRoadTrain) + { + // TODO доделать логику сравнения дополнительных параметров + EntityRoadTrain _x = (EntityRoadTrain)x.EntityTruck; + EntityRoadTrain _y = (EntityRoadTrain)x.EntityTruck; + if (_x.AdditionalColor != _y.AdditionalColor) + { + return false; + } + if (_x.FlashingLights != _y.FlashingLights) + { + return false; + } + if (_x.Ladle != _y.Ladle) + { + return false; + } + } + + return true; + } + + public int GetHashCode([DisallowNull] DrawningTruck obj) + { + return obj.GetHashCode(); + } +} \ No newline at end of file diff --git a/Lab1/Lab1/Drawnings/DrawningCompareByColor.cs b/Lab1/Lab1/Drawnings/DrawningCompareByColor.cs new file mode 100644 index 0000000..015944a --- /dev/null +++ b/Lab1/Lab1/Drawnings/DrawningCompareByColor.cs @@ -0,0 +1,37 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Lab1.Drawnings; + +/// +/// Сравнение по цвету, скорости, весу +/// +internal class DrawningCompareByColor : IComparer +{ + 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); + } +} diff --git a/Lab1/Lab1/Drawnings/DrawningCompareByType.cs b/Lab1/Lab1/Drawnings/DrawningCompareByType.cs new file mode 100644 index 0000000..22fa55d --- /dev/null +++ b/Lab1/Lab1/Drawnings/DrawningCompareByType.cs @@ -0,0 +1,38 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Lab1.Drawnings; + +/// +/// Сравнение по типу, скорости, весу +/// +internal class DrawningCompareByType : IComparer +{ + 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); + } +} \ No newline at end of file diff --git a/Lab1/Lab1/Exceptions/ObjectNotUniqueException.cs b/Lab1/Lab1/Exceptions/ObjectNotUniqueException.cs new file mode 100644 index 0000000..7a71aed --- /dev/null +++ b/Lab1/Lab1/Exceptions/ObjectNotUniqueException.cs @@ -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 Lab1.Exceptions; + +/// +/// Класс, описывающий ошибку переполнения коллекции +/// +[Serializable] +public class ObjectNotUniqueException : ApplicationException +{ + public ObjectNotUniqueException(int count) : base("В коллекции содержится такой же элемент: " + count) { } + public ObjectNotUniqueException() : base() { } + public ObjectNotUniqueException(string message) : base(message) { } + public ObjectNotUniqueException(string message, Exception exception) : base(message, exception) { } + protected ObjectNotUniqueException(SerializationInfo info, StreamingContext contex) : base(info, contex) { } +} \ No newline at end of file diff --git a/Lab1/Lab1/FormTruckCollection.Designer.cs b/Lab1/Lab1/FormTruckCollection.Designer.cs index fd2c3c2..35ca1ff 100644 --- a/Lab1/Lab1/FormTruckCollection.Designer.cs +++ b/Lab1/Lab1/FormTruckCollection.Designer.cs @@ -52,6 +52,8 @@ LoadToolStripMenuItem = new ToolStripMenuItem(); saveFileDialog = new SaveFileDialog(); openFileDialog = new OpenFileDialog(); + buttonSortByType = new Button(); + buttonSortByColor = new Button(); groupBoxTools.SuspendLayout(); panelCompanyTools.SuspendLayout(); panelStorage.SuspendLayout(); @@ -75,6 +77,8 @@ // // panelCompanyTools // + panelCompanyTools.Controls.Add(buttonSortByColor); + panelCompanyTools.Controls.Add(buttonSortByType); panelCompanyTools.Controls.Add(buttonRefresh); panelCompanyTools.Controls.Add(buttonGoToCheck); panelCompanyTools.Controls.Add(buttonRemoveTruck); @@ -88,7 +92,7 @@ // buttonRefresh // buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonRefresh.Location = new Point(16, 216); + buttonRefresh.Location = new Point(16, 152); buttonRefresh.Name = "buttonRefresh"; buttonRefresh.Size = new Size(214, 29); buttonRefresh.TabIndex = 6; @@ -99,7 +103,7 @@ // buttonGoToCheck // buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonGoToCheck.Location = new Point(16, 179); + buttonGoToCheck.Location = new Point(16, 115); buttonGoToCheck.Name = "buttonGoToCheck"; buttonGoToCheck.Size = new Size(214, 31); buttonGoToCheck.TabIndex = 5; @@ -110,7 +114,7 @@ // buttonRemoveTruck // buttonRemoveTruck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonRemoveTruck.Location = new Point(16, 144); + buttonRemoveTruck.Location = new Point(16, 80); buttonRemoveTruck.Name = "buttonRemoveTruck"; buttonRemoveTruck.Size = new Size(214, 29); buttonRemoveTruck.TabIndex = 4; @@ -131,7 +135,7 @@ // // maskedTextBoxPosition // - maskedTextBoxPosition.Location = new Point(16, 111); + maskedTextBoxPosition.Location = new Point(16, 47); maskedTextBoxPosition.Mask = "00"; maskedTextBoxPosition.Name = "maskedTextBoxPosition"; maskedTextBoxPosition.Size = new Size(214, 27); @@ -293,6 +297,30 @@ openFileDialog.FileName = "openFileDialog1"; openFileDialog.Filter = "txt file | *.txt"; // + // buttonSortByType + // + buttonSortByType.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + buttonSortByType.Location = new Point(16, 188); + buttonSortByType.Margin = new Padding(3, 4, 3, 4); + buttonSortByType.Name = "buttonSortByType"; + buttonSortByType.Size = new Size(214, 30); + buttonSortByType.TabIndex = 8; + buttonSortByType.Text = "Сортировка по типу"; + buttonSortByType.UseVisualStyleBackColor = true; + buttonSortByType.Click += buttonSortByType_Click; + // + // buttonSortByColor + // + buttonSortByColor.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + buttonSortByColor.Location = new Point(16, 226); + buttonSortByColor.Margin = new Padding(3, 4, 3, 4); + buttonSortByColor.Name = "buttonSortByColor"; + buttonSortByColor.Size = new Size(214, 29); + buttonSortByColor.TabIndex = 9; + buttonSortByColor.Text = "Сортировка по цвету"; + buttonSortByColor.UseVisualStyleBackColor = true; + buttonSortByColor.Click += buttonSortByColor_Click; + // // FormTruckCollection // AutoScaleDimensions = new SizeF(8F, 20F); @@ -342,5 +370,7 @@ private ToolStripMenuItem LoadToolStripMenuItem; private SaveFileDialog saveFileDialog; private OpenFileDialog openFileDialog; + private Button buttonSortByColor; + private Button buttonSortByType; } } \ No newline at end of file diff --git a/Lab1/Lab1/FormTruckCollection.cs b/Lab1/Lab1/FormTruckCollection.cs index fcf135a..e31c2ba 100644 --- a/Lab1/Lab1/FormTruckCollection.cs +++ b/Lab1/Lab1/FormTruckCollection.cs @@ -84,6 +84,11 @@ public partial class FormTruckCollection : Form MessageBox.Show("Не удалось добавить объект"); _logger.LogError("Ошибка: {Message}", ex.Message); } + catch (ObjectNotUniqueException ex) + { + MessageBox.Show("Не удалось добавить объект, так как такой уже существует"); + _logger.LogError("Ошибка: {Message}", ex.Message); + } } /// @@ -117,7 +122,7 @@ public partial class FormTruckCollection : Form _logger.LogError("Ошибка: {Message}", ex.Message); } } - + /// /// Передача объекта в другую форму /// @@ -242,7 +247,7 @@ public partial class FormTruckCollection : Form listBoxCollection.Items.Clear(); for (int i = 0; i < _storageCollection.Keys?.Count; ++i) { - string? colName = _storageCollection.Keys?[i]; + string? colName = _storageCollection.Keys?[i].Name; if (!string.IsNullOrEmpty(colName)) { listBoxCollection.Items.Add(colName); @@ -315,4 +320,24 @@ public partial class FormTruckCollection : Form } } } + + private void buttonSortByType_Click(object sender, EventArgs e) + { + CompareTruck(new DrawningCompareByType()); + } + + private void buttonSortByColor_Click(object sender, EventArgs e) + { + CompareTruck(new DrawningCompareByColor()); + } + + private void CompareTruck(IComparer comparer) + { + if (_company == null) + { + return; + } + _company.Sort(comparer); + pictureBox.Image = _company.Show(); + } } -- 2.25.1