From e03badef02291951d6c2ae7c405beb7731ba24c4 Mon Sep 17 00:00:00 2001 From: ZakenChannel Date: Mon, 13 May 2024 19:40:12 +0400 Subject: [PATCH] lab 8 done --- .../AbstractCompany.cs | 8 +- .../CollectionInfo.cs | 76 +++++++++++++++++++ .../ICollectionGenericObjects.cs | 16 +++- .../ListGenericObjects.cs | 27 ++++++- .../MassiveGenericObjects.cs | 21 ++++- .../StorageCollection.cs | 49 +++++++----- .../Drawnings/DrawiningPlaneEqutables.cs | 68 +++++++++++++++++ .../Drawnings/DrawningPlaneCompareByColor.cs | 34 +++++++++ .../Drawnings/DrawningPlaneCompareByType.cs | 33 ++++++++ .../Exceptions/ObjectNotUniqueException.cs | 16 ++++ .../FormWarPlaneCollection.Designer.cs | 48 +++++++++--- .../FormWarPlaneCollection.cs | 43 ++++++++++- 12 files changed, 398 insertions(+), 41 deletions(-) create mode 100644 ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/CollectionInfo.cs create mode 100644 ProjectAirFighter/ProjectAirFighter/Drawnings/DrawiningPlaneEqutables.cs create mode 100644 ProjectAirFighter/ProjectAirFighter/Drawnings/DrawningPlaneCompareByColor.cs create mode 100644 ProjectAirFighter/ProjectAirFighter/Drawnings/DrawningPlaneCompareByType.cs create mode 100644 ProjectAirFighter/ProjectAirFighter/Exceptions/ObjectNotUniqueException.cs diff --git a/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/AbstractCompany.cs b/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/AbstractCompany.cs index 61a2c56..9d07f49 100644 --- a/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/AbstractCompany.cs +++ b/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/AbstractCompany.cs @@ -64,7 +64,7 @@ public abstract class AbstractCompany { return -1; } - return company._collection.Insert(plane); + return company._collection.Insert(plane, new DrawiningPlaneEqutables()); } /// @@ -114,6 +114,12 @@ public abstract class AbstractCompany return bitmap; } + /// + /// Сортировка + /// + /// Сравнитель объектов + public void Sort(IComparer comparer) => _collection?.CollectionSort(comparer); + /// /// Вывод заднего фона /// diff --git a/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/CollectionInfo.cs b/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/CollectionInfo.cs new file mode 100644 index 0000000..4dc7755 --- /dev/null +++ b/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/CollectionInfo.cs @@ -0,0 +1,76 @@ +namespace ProjectAirFighter.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(); + } +} diff --git a/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/ICollectionGenericObjects.cs b/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/ICollectionGenericObjects.cs index b4afa10..eb54333 100644 --- a/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/ICollectionGenericObjects.cs +++ b/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/ICollectionGenericObjects.cs @@ -1,4 +1,6 @@ -namespace ProjectAirFighter.CollectionGenericObjects; +using ProjectAirFighter.Drawnings; + +namespace ProjectAirFighter.CollectionGenericObjects; /// /// Интерфейс описания действий для набора хранимых объектов @@ -21,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); /// /// Удаление объекта из коллекции с конкретной позиции @@ -56,4 +60,10 @@ public interface ICollectionGenericObjects /// /// Поэлементый вывод элементов коллекции IEnumerable GetItems(); + + /// + /// Сортировка коллекции + /// + /// Сравнитель объектов + void CollectionSort(IComparer comparer); } diff --git a/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/ListGenericObjects.cs b/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/ListGenericObjects.cs index 7ec37fd..7b0893a 100644 --- a/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/ListGenericObjects.cs +++ b/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/ListGenericObjects.cs @@ -1,5 +1,7 @@  +using ProjectAirFighter.Drawnings; using ProjectAirFighter.Exceptions; +using System.Linq; namespace ProjectAirFighter.CollectionGenericObjects; @@ -54,16 +56,32 @@ public class ListGenericObjects : ICollectionGenericObjects return _collection[position]; } - public int Insert(T obj) + public int Insert(T obj, IEqualityComparer? comparer) { + if (comparer == null) + { + if (_collection.Contains(obj, comparer)) + { + throw new ObjectNotUniqueException(); + } + } + if (Count == _maxCount) { throw new CollectionOverflowException(_collection.Count); } _collection.Add(obj); return Count; } - public int Insert(T obj, int position) + public int Insert(T obj, int position, IEqualityComparer? comparer) { + if (comparer == null) + { + if (_collection.Contains(obj, comparer)) + { + throw new ObjectNotUniqueException(); + } + } + if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(); if (Count == _maxCount) throw new CollectionOverflowException(); _collection.Insert(position, obj); @@ -88,4 +106,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/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/MassiveGenericObjects.cs b/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/MassiveGenericObjects.cs index 16ed97f..9b85900 100644 --- a/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/MassiveGenericObjects.cs @@ -1,4 +1,5 @@  +using ProjectAirFighter.Drawnings; using ProjectAirFighter.Exceptions; namespace ProjectAirFighter.CollectionGenericObjects; @@ -66,12 +67,12 @@ public class MassiveGenericObjects : ICollectionGenericObjects } - public int Insert(T obj) + public int Insert(T obj, IEqualityComparer? comparer) { - return Insert(obj, 0); + return Insert(obj, 0, comparer); } - public int Insert(T obj, int position) + public int Insert(T obj, int position, IEqualityComparer? comparer) { if (position < 0 || position >= Count) { @@ -84,6 +85,15 @@ public class MassiveGenericObjects : ICollectionGenericObjects return position; } + if (comparer != null) + { + foreach (T? item in _collection) + { + if ((comparer as IEqualityComparer).Equals(obj as DrawningWarPlane, item as DrawningWarPlane)) + throw new ObjectNotUniqueException(); + } + } + for (int i = position + 1; i < Count; i++) { if (_collection[i] == null) @@ -129,4 +139,9 @@ public class MassiveGenericObjects : ICollectionGenericObjects yield return _collection[i]; } } + + public void CollectionSort(IComparer comparer) + { + Array.Sort(_collection, comparer); + } } diff --git a/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/StorageCollection.cs b/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/StorageCollection.cs index 6801ccc..e6d7b37 100644 --- a/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/StorageCollection.cs +++ b/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/StorageCollection.cs @@ -1,6 +1,8 @@ -using ProjectAirFighter.Drawnings; +using Microsoft.AspNetCore.Http; +using ProjectAirFighter.Drawnings; using ProjectAirFighter.Exceptions; using System.Text; +using System.Xml.Linq; namespace ProjectAirFighter.CollectionGenericObjects; @@ -14,12 +16,12 @@ public class StorageCollection /// /// Словарь (хранилище) с коллекциями /// - readonly Dictionary> _storages; + readonly Dictionary> _storages; /// /// Возвращение списка названий коллекций /// - public List Keys => _storages.Keys.ToList(); + public List Keys => _storages.Keys.ToList(); /// /// Ключевое слово, с которого должен начинаться файл @@ -42,7 +44,7 @@ public class StorageCollection /// public StorageCollection() { - _storages = new Dictionary>(); + _storages = new Dictionary>(); } /// @@ -52,17 +54,18 @@ public class StorageCollection /// тип коллекции public void AddCollection(string name, CollectionType collectionType) { - if (name == null || _storages.ContainsKey(name)) { return; } + CollectionInfo collectionInfo = new CollectionInfo(name, collectionType, string.Empty); + if (name == null || _storages.ContainsKey(collectionInfo)) { return; } switch (collectionType) { case CollectionType.None: return; case CollectionType.Massive: - _storages.Add(name, new MassiveGenericObjects { }); + _storages.Add(collectionInfo, new MassiveGenericObjects { }); return; case CollectionType.List: - _storages.Add(name, new ListGenericObjects { }); + _storages.Add(collectionInfo, new ListGenericObjects { }); return; } @@ -74,8 +77,9 @@ 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 (name == null || !_storages.ContainsKey(collectionInfo)) { return; } + _storages.Remove(collectionInfo); } /// @@ -87,8 +91,9 @@ 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 (collectionInfo == null || !_storages.ContainsKey(collectionInfo)) { return null; } + return _storages[collectionInfo]; } } @@ -113,17 +118,16 @@ public class StorageCollection using (StreamWriter sw = new StreamWriter(filename)) { sw.WriteLine(_collectionKey.ToString()); - foreach (KeyValuePair> kvpair in _storages) + foreach (KeyValuePair< CollectionInfo, ICollectionGenericObjects > 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; @@ -159,20 +163,25 @@ public class StorageCollection 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); + + CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(record[0]) ?? + throw new Exception("Не удалось определить информацию коллекции:" + record[0]); + + ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionInfo.CollectionType) ?? + throw new Exception("Не удалось определить тип коллекции:" + record[1]); + if (collection == null) { throw new InvalidOperationException("Не удалось определить тип коллекции:" + record[1]); } - 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?.CreateDrawningPlane() is T plane) @@ -187,7 +196,7 @@ public class StorageCollection } } } - _storages.Add(record[0], collection); + _storages.Add(collectionInfo, collection); } } } diff --git a/ProjectAirFighter/ProjectAirFighter/Drawnings/DrawiningPlaneEqutables.cs b/ProjectAirFighter/ProjectAirFighter/Drawnings/DrawiningPlaneEqutables.cs new file mode 100644 index 0000000..8906a18 --- /dev/null +++ b/ProjectAirFighter/ProjectAirFighter/Drawnings/DrawiningPlaneEqutables.cs @@ -0,0 +1,68 @@ +using ProjectAirFighter.Entities; +using System.Diagnostics.CodeAnalysis; + +namespace ProjectAirFighter.Drawnings; + +/// +/// Реализация сравнения двух объектов класса-прорисовки +/// +public class DrawiningPlaneEqutables : IEqualityComparer +{ + public bool Equals(DrawningWarPlane? x, DrawningWarPlane? y) + { + if (x == null || x.EntityFighter == null) + { + return false; + } + + if (y == null || y.EntityFighter == null) + { + return false; + } + + if (x.GetType().Name != y.GetType().Name) + { + return false; + } + + if (x.EntityFighter.Speed != y.EntityFighter.Speed) + { + return false; + } + + if (x.EntityFighter.Weight != y.EntityFighter.Weight) + { + return false; + } + + if (x.EntityFighter.BodyColor != y.EntityFighter.BodyColor) + { + return false; + } + + if (x is DrawningAirFighter && y is DrawningAirFighter) + { + EntityAirFighter _x = (EntityAirFighter) x.EntityFighter; + EntityAirFighter _y = (EntityAirFighter) x.EntityFighter; + if (_x.AdditionalColor != _y.AdditionalColor) + { + return false; + } + if (_x.BodyRockets != _y.BodyRockets) + { + return false; + } + if (_x.AdditionalWings != _y.AdditionalWings) + { + return false; + } + } + + return true; + } + + public int GetHashCode([DisallowNull] DrawningWarPlane obj) + { + return obj.GetHashCode(); + } +} diff --git a/ProjectAirFighter/ProjectAirFighter/Drawnings/DrawningPlaneCompareByColor.cs b/ProjectAirFighter/ProjectAirFighter/Drawnings/DrawningPlaneCompareByColor.cs new file mode 100644 index 0000000..be88cce --- /dev/null +++ b/ProjectAirFighter/ProjectAirFighter/Drawnings/DrawningPlaneCompareByColor.cs @@ -0,0 +1,34 @@ +namespace ProjectAirFighter.Drawnings; + +/// +/// Сравнение по цвету, скорости, весу +/// +public class DrawningPlaneCompareByColor : IComparer +{ + public int Compare(DrawningWarPlane? x, DrawningWarPlane? y) + { + if (x == null || x.EntityFighter == null) + { + return 1; + } + + if (y == null || y.EntityFighter == null) + { + return -1; + } + + var bodycolorCompare = y.EntityFighter.BodyColor.Name.CompareTo(x.EntityFighter.BodyColor.Name); + if (bodycolorCompare != 0) + { + return bodycolorCompare; + } + + var speedCompare = y.EntityFighter.Speed.CompareTo(x.EntityFighter.Speed); + if (speedCompare != 0) + { + return speedCompare; + } + + return y.EntityFighter.Weight.CompareTo(x.EntityFighter.Weight); + } +} diff --git a/ProjectAirFighter/ProjectAirFighter/Drawnings/DrawningPlaneCompareByType.cs b/ProjectAirFighter/ProjectAirFighter/Drawnings/DrawningPlaneCompareByType.cs new file mode 100644 index 0000000..e691444 --- /dev/null +++ b/ProjectAirFighter/ProjectAirFighter/Drawnings/DrawningPlaneCompareByType.cs @@ -0,0 +1,33 @@ +namespace ProjectAirFighter.Drawnings; + +/// +/// Сравнение по типу, скорости, весу +/// +public class DrawningPlaneCompareByType : IComparer +{ + public int Compare(DrawningWarPlane? x, DrawningWarPlane? y) + { + if (x == null || x.EntityFighter == null) + { + return 1; + } + + if (y == null || y.EntityFighter == null) + { + return -1; + } + + if (x.GetType().Name != y.GetType().Name) + { + return y.GetType().Name.CompareTo(x.GetType().Name); + } + + var speedCompare = y.EntityFighter.Speed.CompareTo(x.EntityFighter.Speed); + if (speedCompare != 0) + { + return speedCompare; + } + + return y.EntityFighter.Weight.CompareTo(x.EntityFighter.Weight); + } +} diff --git a/ProjectAirFighter/ProjectAirFighter/Exceptions/ObjectNotUniqueException.cs b/ProjectAirFighter/ProjectAirFighter/Exceptions/ObjectNotUniqueException.cs new file mode 100644 index 0000000..7451621 --- /dev/null +++ b/ProjectAirFighter/ProjectAirFighter/Exceptions/ObjectNotUniqueException.cs @@ -0,0 +1,16 @@ +using System.Runtime.Serialization; + +namespace ProjectAirFighter.Exceptions; + +/// +/// Класс, описывающий ошибку наличия такого же объекта в коллекции +/// +[Serializable] +internal 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) { } +} diff --git a/ProjectAirFighter/ProjectAirFighter/FormWarPlaneCollection.Designer.cs b/ProjectAirFighter/ProjectAirFighter/FormWarPlaneCollection.Designer.cs index a7a8f00..2f03788 100644 --- a/ProjectAirFighter/ProjectAirFighter/FormWarPlaneCollection.Designer.cs +++ b/ProjectAirFighter/ProjectAirFighter/FormWarPlaneCollection.Designer.cs @@ -52,6 +52,8 @@ loadToolStripMenuItem = new ToolStripMenuItem(); saveFileDialog = new SaveFileDialog(); openFileDialog = new OpenFileDialog(); + buttonSortByColor = new Button(); + buttonSortByType = new Button(); groupBoxTools.SuspendLayout(); panelCompanyTools.SuspendLayout(); panelStorage.SuspendLayout(); @@ -66,9 +68,9 @@ groupBoxTools.Controls.Add(panelStorage); groupBoxTools.Controls.Add(comboBoxSelectorCompany); groupBoxTools.Dock = DockStyle.Right; - groupBoxTools.Location = new Point(978, 24); + groupBoxTools.Location = new Point(980, 24); groupBoxTools.Name = "groupBoxTools"; - groupBoxTools.Size = new Size(236, 621); + groupBoxTools.Size = new Size(236, 656); groupBoxTools.TabIndex = 0; groupBoxTools.TabStop = false; groupBoxTools.Text = "Инструменты"; @@ -85,6 +87,8 @@ // // panelCompanyTools // + panelCompanyTools.Controls.Add(buttonSortByColor); + panelCompanyTools.Controls.Add(buttonSortByType); panelCompanyTools.Controls.Add(buttonAddFighter); panelCompanyTools.Controls.Add(maskedTextBox); panelCompanyTools.Controls.Add(buttonRefresh); @@ -94,7 +98,7 @@ panelCompanyTools.Enabled = false; panelCompanyTools.Location = new Point(3, 336); panelCompanyTools.Name = "panelCompanyTools"; - panelCompanyTools.Size = new Size(230, 282); + panelCompanyTools.Size = new Size(230, 317); panelCompanyTools.TabIndex = 11; // // buttonAddFighter @@ -110,7 +114,7 @@ // // maskedTextBox // - maskedTextBox.Location = new Point(2, 107); + maskedTextBox.Location = new Point(2, 58); maskedTextBox.Mask = "00"; maskedTextBox.Name = "maskedTextBox"; maskedTextBox.Size = new Size(224, 23); @@ -120,7 +124,7 @@ // buttonRefresh // buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonRefresh.Location = new Point(2, 232); + buttonRefresh.Location = new Point(2, 183); buttonRefresh.Name = "buttonRefresh"; buttonRefresh.Size = new Size(224, 42); buttonRefresh.TabIndex = 6; @@ -131,7 +135,7 @@ // buttonRemoveFighter // buttonRemoveFighter.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonRemoveFighter.Location = new Point(2, 136); + buttonRemoveFighter.Location = new Point(2, 87); buttonRemoveFighter.Name = "buttonRemoveFighter"; buttonRemoveFighter.Size = new Size(224, 42); buttonRemoveFighter.TabIndex = 4; @@ -142,7 +146,7 @@ // buttonGoToCheck // buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonGoToCheck.Location = new Point(2, 184); + buttonGoToCheck.Location = new Point(2, 135); buttonGoToCheck.Name = "buttonGoToCheck"; buttonGoToCheck.Size = new Size(224, 42); buttonGoToCheck.TabIndex = 5; @@ -249,7 +253,7 @@ pictureBox.Dock = DockStyle.Fill; pictureBox.Location = new Point(0, 24); pictureBox.Name = "pictureBox"; - pictureBox.Size = new Size(978, 621); + pictureBox.Size = new Size(980, 656); pictureBox.TabIndex = 1; pictureBox.TabStop = false; // @@ -258,7 +262,7 @@ menuStrip.Items.AddRange(new ToolStripItem[] { FileToolStripMenuItem }); menuStrip.Location = new Point(0, 0); menuStrip.Name = "menuStrip"; - menuStrip.Size = new Size(1214, 24); + menuStrip.Size = new Size(1216, 24); menuStrip.TabIndex = 2; menuStrip.Text = "menuStrip1"; // @@ -293,11 +297,33 @@ // openFileDialog.Filter = "txt file | *.txt"; // + // buttonSortByColor + // + buttonSortByColor.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + buttonSortByColor.Location = new Point(3, 275); + buttonSortByColor.Name = "buttonSortByColor"; + buttonSortByColor.Size = new Size(224, 42); + buttonSortByColor.TabIndex = 8; + buttonSortByColor.Text = "Сортировка по цвету"; + buttonSortByColor.UseVisualStyleBackColor = true; + buttonSortByColor.Click += ButtonSortByColor_Click; + // + // buttonSortByType + // + buttonSortByType.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + buttonSortByType.Location = new Point(3, 227); + buttonSortByType.Name = "buttonSortByType"; + buttonSortByType.Size = new Size(224, 42); + buttonSortByType.TabIndex = 7; + buttonSortByType.Text = "Сортировка по типу"; + buttonSortByType.UseVisualStyleBackColor = true; + buttonSortByType.Click += ButtonSortByType_Click; + // // FormWarPlaneCollection // AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(1214, 645); + ClientSize = new Size(1216, 680); Controls.Add(pictureBox); Controls.Add(groupBoxTools); Controls.Add(menuStrip); @@ -342,5 +368,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/ProjectAirFighter/ProjectAirFighter/FormWarPlaneCollection.cs b/ProjectAirFighter/ProjectAirFighter/FormWarPlaneCollection.cs index ab754ba..3096f1a 100644 --- a/ProjectAirFighter/ProjectAirFighter/FormWarPlaneCollection.cs +++ b/ProjectAirFighter/ProjectAirFighter/FormWarPlaneCollection.cs @@ -2,7 +2,6 @@ using ProjectAirFighter.CollectionGenericObjects; using ProjectAirFighter.Drawnings; using ProjectAirFighter.Exceptions; -using System.Windows.Forms; namespace ProjectAirFighter; @@ -74,6 +73,11 @@ public partial class FormWarPlaneCollection : Form MessageBox.Show("Ошибка переполнения коллекции"); _logger.LogError("Ошибка: {Message}", ex.Message); } + catch (ObjectNotUniqueException ex) + { + MessageBox.Show("Такой объект уже присутствует в коллекции"); + _logger.LogError("Ошибка: {Message}", ex.Message); + } } /// @@ -236,7 +240,7 @@ public partial class FormWarPlaneCollection : 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); @@ -323,4 +327,39 @@ public partial class FormWarPlaneCollection : Form } } } + + /// + /// Сортировка по типу + /// + /// + /// + private void ButtonSortByType_Click(object sender, EventArgs e) + { + ComparePlanes(new DrawningPlaneCompareByType()); + } + + /// + /// Сортировка по цвету + /// + /// + /// + private void ButtonSortByColor_Click(object sender, EventArgs e) + { + ComparePlanes(new DrawningPlaneCompareByColor()); + } + + /// + /// Сортировка по сравнителю + /// + /// Сравнитель объектов + private void ComparePlanes(IComparer comparer) + { + if (_company == null) + { + return; + } + + _company.Sort(comparer); + pictureBox.Image = _company.Show(); + } }