From c7a6718b9934195d59f768e814f097eeacc0ec43 Mon Sep 17 00:00:00 2001 From: 5_fG Date: Wed, 5 Jun 2024 18:16:12 +0400 Subject: [PATCH] =?UTF-8?q?=D0=9B=D0=B0=D0=B1=D0=BE=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=20=E2=84=96=208?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../AbstractCompany.cs | 8 +- .../CollectionInfo.cs | 76 +++++++++++++++++++ .../ICollectionGenericObjects.cs | 12 ++- .../ListGenericObjects.cs | 19 ++++- .../MassiveGenericObjects.cs | 26 ++++++- .../StorageCollection.cs | 55 ++++++++------ .../DrawningTrackedVehicleCompareByColor.cs | 34 +++++++++ .../DrawningTrackedVehicleCompareByType.cs | 37 +++++++++ .../DrawningTrackedVehicleEqutables.cs | 67 ++++++++++++++++ .../ExtentionDrawningTrackedVehicle.cs | 4 +- .../Exceptions/ObjectExistsException.cs | 20 +++++ .../FormExcavatorCollection.Designer.cs | 38 ++++++++-- .../FormExcavatorCollection.cs | 45 ++++++++++- 13 files changed, 396 insertions(+), 45 deletions(-) create mode 100644 ProjectExcavator/ProjectExcavator/CollectionGenericObjects/CollectionInfo.cs create mode 100644 ProjectExcavator/ProjectExcavator/Drawnings/DrawningTrackedVehicleCompareByColor.cs create mode 100644 ProjectExcavator/ProjectExcavator/Drawnings/DrawningTrackedVehicleCompareByType.cs create mode 100644 ProjectExcavator/ProjectExcavator/Drawnings/DrawningTrackedVehicleEqutables.cs create mode 100644 ProjectExcavator/ProjectExcavator/Exceptions/ObjectExistsException.cs diff --git a/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/AbstractCompany.cs b/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/AbstractCompany.cs index 703d68e..a55f01d 100644 --- a/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/AbstractCompany.cs +++ b/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/AbstractCompany.cs @@ -59,7 +59,7 @@ public abstract class AbstractCompany /// public static int operator +(AbstractCompany company, DrawningTrackedVehicle excavator) { - return company._collection.Insert(excavator); + return company._collection.Insert(excavator, new DrawningTrackedVehicleEqutables()); } /// @@ -103,6 +103,12 @@ public abstract class AbstractCompany return bitmap; } + /// + /// Сортировка + /// + /// Сравнитель объектов + public void Sort(IComparer comparer) => _collection?.CollectionSort(comparer); + /// /// Вывод заднего фона /// diff --git a/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/CollectionInfo.cs b/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/CollectionInfo.cs new file mode 100644 index 0000000..535cbcb --- /dev/null +++ b/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/CollectionInfo.cs @@ -0,0 +1,76 @@ +namespace ProjectExcavator.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/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/ICollectionGenericObjects.cs b/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/ICollectionGenericObjects.cs index 18a2d07..b6376f1 100644 --- a/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/ICollectionGenericObjects.cs +++ b/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/ICollectionGenericObjects.cs @@ -21,16 +21,18 @@ public interface ICollectionGenericObjects /// Добавление объекта в коллекцию /// /// Добавляемый объект + /// Сравнение двух объектов /// true - вставка прошла удачно, false - вставка не удалась - int Insert(T obj); + int Insert(T obj, IEqualityComparer? comparer = null); /// /// Добавление объекта в коллекцию на конкретную позицию /// /// Добавляемый объект /// Позиция + /// Сравнение двух объектов /// true - вставка прошла удачно, false - вставка не удалась - int Insert(T obj, int position); + int Insert(T obj, int position, IEqualityComparer? comparer = null); /// /// Удаление объекта из коллекции с конкретной позиции @@ -56,4 +58,10 @@ public interface ICollectionGenericObjects /// /// Поэлементый вывод элементов коллекции IEnumerable GetItems(); + + /// + /// Сортировка коллекции + /// + /// Сравнитель объектов + void CollectionSort(IComparer comparer); } diff --git a/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/ListGenericObjects.cs b/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/ListGenericObjects.cs index 9289106..ece661b 100644 --- a/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/ListGenericObjects.cs +++ b/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/ListGenericObjects.cs @@ -48,7 +48,7 @@ public class ListGenericObjects : ICollectionGenericObjects return _collection[position]; } - public int Insert(T obj) + public int Insert(T obj,IEqualityComparer? comparer = null) { //проверка, что не превышено максимальное количество элементов //вставка в конец набора @@ -57,13 +57,17 @@ public class ListGenericObjects : ICollectionGenericObjects { throw new CollectionOverflowException(); } + if (_collection.Contains(obj, comparer)) + { + throw new ObjectExistsException(); + } _collection.Add(obj); return 1; } - public int Insert(T obj, int position) - { + public int Insert(T obj, int position, IEqualityComparer? comparer = null) + { // проверка, что не превышено максимальное количество элементов // проверка позиции // вставка по позиции @@ -76,6 +80,10 @@ public class ListGenericObjects : ICollectionGenericObjects { throw new PositionOutOfCollectionException(); } + if (_collection.Contains(obj, comparer)) + { + throw new ObjectExistsException(position); + } _collection.Insert(position, obj); return 1; } @@ -100,4 +108,9 @@ public class ListGenericObjects : ICollectionGenericObjects yield return _collection[i]; } } + + public void CollectionSort(IComparer comparer) + { + _collection.Sort(comparer); + } } \ No newline at end of file diff --git a/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/MassiveGenericObjects.cs b/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/MassiveGenericObjects.cs index eabbc89..e5adff7 100644 --- a/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/MassiveGenericObjects.cs @@ -1,4 +1,5 @@ using ProjectExcavator.Exceptions; + namespace ProjectExcavator.CollectionGenericObjects; /// @@ -61,14 +62,18 @@ public class MassiveGenericObjects : ICollectionGenericObjects } } - public int Insert(T obj) + public int Insert(T obj, IEqualityComparer? comparer = null) { //Вставка в свободное место набора - + int index = Array.IndexOf(_collection, null); + if (_collection.Contains(obj, comparer)) + { + throw new ObjectExistsException(index); + } return Insert(obj, 0); } - public int Insert(T obj, int position) + public int Insert(T obj, int position, IEqualityComparer? comparer = null) { //Проверка позиции //Проверка, что элемент массива по этой позиции пустой, если нет, то @@ -77,6 +82,11 @@ public class MassiveGenericObjects : ICollectionGenericObjects if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position); + if (_collection.Contains(obj, comparer)) + { + throw new ObjectExistsException(position); + } + if (_collection[position] == null) { _collection[position] = obj; @@ -133,4 +143,14 @@ public class MassiveGenericObjects : ICollectionGenericObjects yield return _collection[i]; } } + + public void CollectionSort(IComparer comparer) + { + if (_collection?.Length > 0) + { + Array.Sort(_collection, comparer); + Array.Reverse(_collection); + } + + } } diff --git a/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/StorageCollection.cs b/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/StorageCollection.cs index e8b773b..2e5cb5c 100644 --- a/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/StorageCollection.cs +++ b/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/StorageCollection.cs @@ -11,16 +11,16 @@ namespace ProjectExcavator.CollectionGenericObjects; public class StorageCollection where T : DrawningTrackedVehicle { - /// - /// Словарь (хранилище) с коллекциями - /// - readonly Dictionary> _storages; + /// + /// Словарь (хранилище) с коллекциями + /// + Dictionary> _storages; /// /// Возвращение списка названий коллекций /// - public List Keys => _storages.Keys.ToList(); + public List Keys => _storages.Keys.ToList(); /// /// Ключевое слово, с которого должен начинаться файл @@ -43,7 +43,7 @@ public class StorageCollection /// public StorageCollection() { - _storages = new Dictionary>(); + _storages = new Dictionary>(); } /// @@ -53,7 +53,8 @@ public class StorageCollection /// тип коллекции public void AddCollection(string name, CollectionType collectionType) { - if (name == null || _storages.ContainsKey(name)) + CollectionInfo collectionInfo = new CollectionInfo(name, collectionType, string.Empty); + if (collectionInfo.Name == null || _storages.ContainsKey(collectionInfo)) { return; } @@ -64,10 +65,10 @@ public class StorageCollection case CollectionType.None: return; case CollectionType.List: - _storages.Add(name, new ListGenericObjects { }); + _storages.Add(collectionInfo, new ListGenericObjects { }); return; case CollectionType.Massive: - _storages.Add(name, new MassiveGenericObjects { }); + _storages.Add(collectionInfo, new MassiveGenericObjects { }); return; } } @@ -79,8 +80,12 @@ public class StorageCollection /// Название коллекции public void DelCollection(string name) { - if (name == null || !_storages.ContainsKey(name)) { return; } - _storages.Remove(name); + CollectionInfo collectionInfo = new CollectionInfo(name, CollectionType.None, string.Empty); + if (collectionInfo.Name == null || _storages.ContainsKey(collectionInfo)) + { + return; + } + _storages.Remove(collectionInfo); } /// @@ -93,8 +98,9 @@ public class StorageCollection { get { - if (name == null || !_storages.ContainsKey(name)) { return null; } - return _storages[name]; + CollectionInfo collectionInfo = new CollectionInfo(name, CollectionType.None, ""); + if (collectionInfo == null || !_storages.ContainsKey(collectionInfo)) { return null; } + return _storages[collectionInfo]; } } @@ -121,17 +127,16 @@ public class StorageCollection using (StreamWriter fs = new StreamWriter(filename)) { fs.WriteLine(_collectionKey.ToString()); - foreach (KeyValuePair> kvpair in _storages) + foreach (KeyValuePair> kvpair in _storages) { // не сохраняем пустые коллекции if (kvpair.Value.Count == 0) continue; sb.Append(kvpair.Key); sb.Append(_separatorForKeyValue); - sb.Append(kvpair.Value.GetCollectionType); - sb.Append(_separatorForKeyValue); sb.Append(kvpair.Value.MaxCount); sb.Append(_separatorForKeyValue); + foreach (T? item in kvpair.Value.GetItems()) { string data = item?.GetDataForSave() ?? string.Empty; @@ -166,24 +171,24 @@ public class StorageCollection throw new ArgumentException("В файле нет данных"); if (str != _collectionKey.ToString()) throw new InvalidDataException("В файле неверные данные"); + _storages.Clear(); while ((str = sr.ReadLine()) != null) { 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); - if (collection == null) - { - throw new InvalidOperationException("Не удалось создать коллекцию"); - } + CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(record[0]) ?? + throw new Exception("Не удалось определить информацию коллекции:" + record[0]); + ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionInfo.CollectionType) ?? + throw new Exception("Не удалось определить тип коллекции:" + record[1]); + collection.MaxCount = Convert.ToInt32(record[1]); collection.MaxCount = Convert.ToInt32(record[2]); - string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); + string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); foreach (string elem in set) { if (elem?.CreateDrawningTrackedVehicle() is T trackedVehicle) @@ -199,7 +204,7 @@ public class StorageCollection } } } - _storages.Add(record[0], collection); + _storages.Add(collectionInfo, collection); } } } diff --git a/ProjectExcavator/ProjectExcavator/Drawnings/DrawningTrackedVehicleCompareByColor.cs b/ProjectExcavator/ProjectExcavator/Drawnings/DrawningTrackedVehicleCompareByColor.cs new file mode 100644 index 0000000..dd85907 --- /dev/null +++ b/ProjectExcavator/ProjectExcavator/Drawnings/DrawningTrackedVehicleCompareByColor.cs @@ -0,0 +1,34 @@ +namespace ProjectExcavator.Drawnings; + +/// +/// Сравнение по цвету, скорости, весу +/// +public class DrawningTrackedVehicleCompareByColor : IComparer +{ + public int Compare(DrawningTrackedVehicle? x, DrawningTrackedVehicle? y) + { + if (x == null && y == null) + { + return 0; + } + if (x == null || x.EntityTrackedVehicle == null) + { + return -1; + } + + if (y == null || y.EntityTrackedVehicle == null) + { + return 1; + } + if(x.EntityTrackedVehicle.BodyColor.Name != y.EntityTrackedVehicle.BodyColor.Name) + { + return x.EntityTrackedVehicle.BodyColor.Name.CompareTo(y.EntityTrackedVehicle.BodyColor.Name); + } + var speedCompare = x.EntityTrackedVehicle.Speed.CompareTo(y.EntityTrackedVehicle.Speed); + if (speedCompare != 0) + { + return speedCompare; + } + return x.EntityTrackedVehicle.Weight.CompareTo(y.EntityTrackedVehicle.Weight); + } +} \ No newline at end of file diff --git a/ProjectExcavator/ProjectExcavator/Drawnings/DrawningTrackedVehicleCompareByType.cs b/ProjectExcavator/ProjectExcavator/Drawnings/DrawningTrackedVehicleCompareByType.cs new file mode 100644 index 0000000..8e4d8ba --- /dev/null +++ b/ProjectExcavator/ProjectExcavator/Drawnings/DrawningTrackedVehicleCompareByType.cs @@ -0,0 +1,37 @@ +namespace ProjectExcavator.Drawnings; +/// +/// Сравнение по типу, скорости, весу +/// +public class DrawningTrackedVehicleCompareByType : IComparer +{ + public int Compare(DrawningTrackedVehicle? x, DrawningTrackedVehicle? y) + { + if (x == null && y == null) + { + return 0; + } + if (x == null || x.EntityTrackedVehicle == null) + { + return -1; + } + + if (y == null || y.EntityTrackedVehicle == null) + { + return 1; + } + + if (!x.GetType().Name.Equals(y.GetType().Name)) + { + return x.GetType().Name.CompareTo(y.GetType().Name); + } + + var speedCompare = x.EntityTrackedVehicle.Speed.CompareTo(y.EntityTrackedVehicle.Speed); + if (speedCompare != 0) + { + return speedCompare; + } + + + return x.EntityTrackedVehicle.Weight.CompareTo(y.EntityTrackedVehicle.Weight); + } +} \ No newline at end of file diff --git a/ProjectExcavator/ProjectExcavator/Drawnings/DrawningTrackedVehicleEqutables.cs b/ProjectExcavator/ProjectExcavator/Drawnings/DrawningTrackedVehicleEqutables.cs new file mode 100644 index 0000000..d847f1f --- /dev/null +++ b/ProjectExcavator/ProjectExcavator/Drawnings/DrawningTrackedVehicleEqutables.cs @@ -0,0 +1,67 @@ +using ProjectExcavator.Entities; +using System.Diagnostics.CodeAnalysis; + +namespace ProjectExcavator.Drawnings; + +/// +/// Реализация сравнения двух объектов класса-прорисовки +/// +public class DrawningTrackedVehicleEqutables : IEqualityComparer +{ + public bool Equals(DrawningTrackedVehicle? x, DrawningTrackedVehicle? y) + { + if (x == null || x.EntityTrackedVehicle == null) + { + return false; + } + + if (y == null || y.EntityTrackedVehicle == null) + { + return false; + } + + if (x.GetType().Name != y.GetType().Name) + { + return false; + } + + if (x.EntityTrackedVehicle.Speed != y.EntityTrackedVehicle.Speed) + { + return false; + } + + if (x.EntityTrackedVehicle.Weight != y.EntityTrackedVehicle.Weight) + { + return false; + } + + if (x.EntityTrackedVehicle.BodyColor != y.EntityTrackedVehicle.BodyColor) + { + return false; + } + if (x is DrawningExcavator && y is DrawningExcavator) + { + EntityExcavator entityX = (EntityExcavator)x.EntityTrackedVehicle; + EntityExcavator entityY = (EntityExcavator)y.EntityTrackedVehicle; + if(entityX.Bucket != entityY.Bucket) + { + return false; + } + if(entityX.Supports != entityY.Supports) + { + return false; + } + if(entityX.AdditionalColor != entityY.AdditionalColor) + { + return false; + } + } + + return true; + } + + public int GetHashCode([DisallowNull] DrawningTrackedVehicle obj) + { + return obj.GetHashCode(); + } +} \ No newline at end of file diff --git a/ProjectExcavator/ProjectExcavator/Drawnings/ExtentionDrawningTrackedVehicle.cs b/ProjectExcavator/ProjectExcavator/Drawnings/ExtentionDrawningTrackedVehicle.cs index fc4c3b2..914e485 100644 --- a/ProjectExcavator/ProjectExcavator/Drawnings/ExtentionDrawningTrackedVehicle.cs +++ b/ProjectExcavator/ProjectExcavator/Drawnings/ExtentionDrawningTrackedVehicle.cs @@ -1,5 +1,5 @@ -using ProjectExcavator.Drawnings; -using ProjectExcavator.Entities; +using ProjectExcavator.Entities; +namespace ProjectExcavator.Drawnings; /// /// Расширение для класса TrackedVehicle diff --git a/ProjectExcavator/ProjectExcavator/Exceptions/ObjectExistsException.cs b/ProjectExcavator/ProjectExcavator/Exceptions/ObjectExistsException.cs new file mode 100644 index 0000000..90e3cfc --- /dev/null +++ b/ProjectExcavator/ProjectExcavator/Exceptions/ObjectExistsException.cs @@ -0,0 +1,20 @@ +using System.Runtime.Serialization; + +namespace ProjectExcavator.Exceptions; + +/// +/// Класс, описывающий ошибку переполнения коллекции +/// +[Serializable] +internal class ObjectExistsException : ApplicationException +{ + public ObjectExistsException(int count) : base("Вставка существуюзего объекта") { } + + public ObjectExistsException() : base() { } + + public ObjectExistsException(string message) : base(message) { } + + public ObjectExistsException(string message, Exception exception) : base(message, exception) { } + + protected ObjectExistsException(SerializationInfo info, StreamingContext contex) : base(info, contex) { } +} \ No newline at end of file diff --git a/ProjectExcavator/ProjectExcavator/FormExcavatorCollection.Designer.cs b/ProjectExcavator/ProjectExcavator/FormExcavatorCollection.Designer.cs index a27b209..d1c837c 100644 --- a/ProjectExcavator/ProjectExcavator/FormExcavatorCollection.Designer.cs +++ b/ProjectExcavator/ProjectExcavator/FormExcavatorCollection.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(buttonAddTrackedVehicle); panelCompanyTools.Controls.Add(buttonRefresh); panelCompanyTools.Controls.Add(maskedTextBoxPosition); @@ -100,9 +104,9 @@ // buttonRefresh // buttonRefresh.Anchor = AnchorStyles.Top; - buttonRefresh.Location = new Point(3, 240); + buttonRefresh.Location = new Point(1, 174); buttonRefresh.Name = "buttonRefresh"; - buttonRefresh.Size = new Size(215, 40); + buttonRefresh.Size = new Size(215, 30); buttonRefresh.TabIndex = 6; buttonRefresh.Text = "Обновить"; buttonRefresh.UseVisualStyleBackColor = true; @@ -111,7 +115,7 @@ // maskedTextBoxPosition // maskedTextBoxPosition.Anchor = AnchorStyles.Top; - maskedTextBoxPosition.Location = new Point(3, 115); + maskedTextBoxPosition.Location = new Point(4, 59); maskedTextBoxPosition.Mask = "00"; maskedTextBoxPosition.Name = "maskedTextBoxPosition"; maskedTextBoxPosition.Size = new Size(215, 27); @@ -121,9 +125,9 @@ // buttonGoToCheck // buttonGoToCheck.Anchor = AnchorStyles.Top; - buttonGoToCheck.Location = new Point(3, 194); + buttonGoToCheck.Location = new Point(4, 138); buttonGoToCheck.Name = "buttonGoToCheck"; - buttonGoToCheck.Size = new Size(215, 40); + buttonGoToCheck.Size = new Size(214, 30); buttonGoToCheck.TabIndex = 5; buttonGoToCheck.Text = "Передать на тесты"; buttonGoToCheck.UseVisualStyleBackColor = true; @@ -132,7 +136,7 @@ // ButtonRemoveExcavator // ButtonRemoveExcavator.Anchor = AnchorStyles.Top; - ButtonRemoveExcavator.Location = new Point(3, 148); + ButtonRemoveExcavator.Location = new Point(3, 92); ButtonRemoveExcavator.Name = "ButtonRemoveExcavator"; ButtonRemoveExcavator.Size = new Size(215, 40); ButtonRemoveExcavator.TabIndex = 4; @@ -306,6 +310,26 @@ openFileDialog.FileName = "openFileDialog1"; openFileDialog.Filter = "txt file | *.txt"; // + // buttonSortByType + // + buttonSortByType.Location = new Point(1, 210); + buttonSortByType.Name = "buttonSortByType"; + buttonSortByType.Size = new Size(215, 27); + buttonSortByType.TabIndex = 8; + buttonSortByType.Text = "Сортировка по типу"; + buttonSortByType.UseVisualStyleBackColor = true; + buttonSortByType.Click += ButtonSortByType_Click; + // + // buttonSortByColor + // + buttonSortByColor.Location = new Point(3, 243); + buttonSortByColor.Name = "buttonSortByColor"; + buttonSortByColor.Size = new Size(213, 27); + buttonSortByColor.TabIndex = 9; + buttonSortByColor.Text = "Сортировка по цвету"; + buttonSortByColor.UseVisualStyleBackColor = true; + buttonSortByColor.Click += ButtonSortByColor_Click; + // // FormExcavatorCollection // AutoScaleDimensions = new SizeF(8F, 20F); @@ -355,5 +379,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/ProjectExcavator/ProjectExcavator/FormExcavatorCollection.cs b/ProjectExcavator/ProjectExcavator/FormExcavatorCollection.cs index 1fa4013..4df966b 100644 --- a/ProjectExcavator/ProjectExcavator/FormExcavatorCollection.cs +++ b/ProjectExcavator/ProjectExcavator/FormExcavatorCollection.cs @@ -82,12 +82,16 @@ public partial class FormExcavatorCollection : Form _logger.LogInformation("Добавлен объект: " + trackedVehicle.GetDataForSave()); } } - //catch (ObjectNotFoundException) { } catch (CollectionOverflowException ex) { - MessageBox.Show("В коллекции превышено допустимое количество элементов:" ); + MessageBox.Show("В коллекции превышено допустимое количество элементов:"); _logger.LogWarning($"Не удалось добавить объект: {ex.Message}"); } + catch (ObjectExistsException ex) + { + MessageBox.Show("Такой объект есть в коллекции"); + _logger.LogWarning($"Добавление существующего объекта: {ex.Message}"); + } } /// @@ -256,7 +260,7 @@ public partial class FormExcavatorCollection : Form 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); @@ -342,4 +346,39 @@ public partial class FormExcavatorCollection : Form } } } + + /// + /// Сортировка по цвету + /// + /// + /// + private void ButtonSortByColor_Click(object sender, EventArgs e) + { + CompareCars(new DrawningTrackedVehicleCompareByColor()); + } + + /// + /// Сортировка по типу + /// + /// + /// + private void ButtonSortByType_Click(object sender, EventArgs e) + { + CompareCars(new DrawningTrackedVehicleCompareByType()); + } + + /// + /// Сортировка по сравнителю + /// + /// Сравнитель объектов + private void CompareCars(IComparer comparer) + { + if (_company == null) + { + return; + } + + _company.Sort(comparer); + pictureBox.Image = _company.Show(); + } } -- 2.25.1