From bf928927e9da3c9ab130401d607af30b64b803f7 Mon Sep 17 00:00:00 2001 From: ilyaryabovv Date: Wed, 22 May 2024 20:45:45 +0400 Subject: [PATCH] =?UTF-8?q?=D0=BB=D0=B0=D0=B1=208?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../AbstractCompany.cs | 7 ++- .../CollectionInfo.cs | 45 +++++++++++++++ .../ICollectionGenericObjects.cs | 12 +++- .../ListGenericObjects.cs | 23 +++++++- .../MassiveGenericObjects.cs | 24 +++++++- .../StorageCollection.cs | 39 +++++++------ .../DrawingBaseStormtrooperCompareByColor.cs | 28 +++++++++ .../DrawingBaseStormtrooperCompareByType.cs | 35 ++++++++++++ .../DrawingBaseStormtrooperEqutables.cs | 57 +++++++++++++++++++ .../Exceptions/ObjectIsEqualException.cs | 14 +++++ .../FormStormtrooperCollection.Designer.cs | 46 +++++++++++---- .../FormStormtrooperCollection.cs | 41 ++++++++++--- 12 files changed, 327 insertions(+), 44 deletions(-) create mode 100644 ProjectStormtrooper/ProjectStormtrooper/CollectionGenericObjects/CollectionInfo.cs create mode 100644 ProjectStormtrooper/ProjectStormtrooper/Drawnings/DrawingBaseStormtrooperCompareByColor.cs create mode 100644 ProjectStormtrooper/ProjectStormtrooper/Drawnings/DrawingBaseStormtrooperCompareByType.cs create mode 100644 ProjectStormtrooper/ProjectStormtrooper/Drawnings/DrawingBaseStormtrooperEqutables.cs create mode 100644 ProjectStormtrooper/ProjectStormtrooper/Exceptions/ObjectIsEqualException.cs diff --git a/ProjectStormtrooper/ProjectStormtrooper/CollectionGenericObjects/AbstractCompany.cs b/ProjectStormtrooper/ProjectStormtrooper/CollectionGenericObjects/AbstractCompany.cs index 0fc31a8..c3c3abf 100644 --- a/ProjectStormtrooper/ProjectStormtrooper/CollectionGenericObjects/AbstractCompany.cs +++ b/ProjectStormtrooper/ProjectStormtrooper/CollectionGenericObjects/AbstractCompany.cs @@ -62,7 +62,7 @@ public abstract class AbstractCompany /// public static int operator +(AbstractCompany company, DrawningBaseStormtrooper stormtrooper) { - return company._collection.Insert(stormtrooper); + return company._collection.Insert(stormtrooper, new DrawingBaseStormtrooperEqutables()); } /// @@ -118,4 +118,9 @@ public abstract class AbstractCompany /// Расстановка объектов /// protected abstract void SetObjectsPosition(); + /// + /// Сортировка + /// + /// Сравнитель объектов + public void Sort(IComparer comparer) => _collection?.CollectionSort(comparer); } \ No newline at end of file diff --git a/ProjectStormtrooper/ProjectStormtrooper/CollectionGenericObjects/CollectionInfo.cs b/ProjectStormtrooper/ProjectStormtrooper/CollectionGenericObjects/CollectionInfo.cs new file mode 100644 index 0000000..9e03bfa --- /dev/null +++ b/ProjectStormtrooper/ProjectStormtrooper/CollectionGenericObjects/CollectionInfo.cs @@ -0,0 +1,45 @@ + + +namespace ProjectStormtrooper.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; + } + 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/ProjectStormtrooper/ProjectStormtrooper/CollectionGenericObjects/ICollectionGenericObjects.cs b/ProjectStormtrooper/ProjectStormtrooper/CollectionGenericObjects/ICollectionGenericObjects.cs index e441b76..9a83c3e 100644 --- a/ProjectStormtrooper/ProjectStormtrooper/CollectionGenericObjects/ICollectionGenericObjects.cs +++ b/ProjectStormtrooper/ProjectStormtrooper/CollectionGenericObjects/ICollectionGenericObjects.cs @@ -21,16 +21,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); /// /// Удаление объекта из коллекции с конкретной позиции @@ -55,4 +57,10 @@ public interface ICollectionGenericObjects /// /// Поэлементый вывод элементов коллекции IEnumerable GetItems(); + /// + /// Сортировка коллекции + /// + /// Сравнитель объектов + void CollectionSort(IComparer comparer); + } \ No newline at end of file diff --git a/ProjectStormtrooper/ProjectStormtrooper/CollectionGenericObjects/ListGenericObjects.cs b/ProjectStormtrooper/ProjectStormtrooper/CollectionGenericObjects/ListGenericObjects.cs index 4a0c4d3..49566a8 100644 --- a/ProjectStormtrooper/ProjectStormtrooper/CollectionGenericObjects/ListGenericObjects.cs +++ b/ProjectStormtrooper/ProjectStormtrooper/CollectionGenericObjects/ListGenericObjects.cs @@ -47,17 +47,31 @@ where T : class if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position); return _collection[position]; } - public int Insert(T obj) + public int Insert(T obj, IEqualityComparer? comparer = null) { // TODO выброс ошибки если переполнение + if (comparer != null) + { + if (_collection.Contains(obj, comparer)) + { + throw new ObjectIsEqualException(); + } + } 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 выброс ошибки если за границу + if (comparer != null) + { + if (_collection.Contains(obj, comparer)) + { + throw new ObjectIsEqualException(); + } + } if (Count == _maxCount) throw new CollectionOverflowException(Count); if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position); _collection.Insert(position, obj); @@ -80,6 +94,11 @@ where T : class yield return _collection[i]; } } + + void ICollectionGenericObjects.CollectionSort(IComparer comparer) + { + _collection.Sort(comparer); + } } diff --git a/ProjectStormtrooper/ProjectStormtrooper/CollectionGenericObjects/MassiveGenericObjects.cs b/ProjectStormtrooper/ProjectStormtrooper/CollectionGenericObjects/MassiveGenericObjects.cs index a5a2093..60cb958 100644 --- a/ProjectStormtrooper/ProjectStormtrooper/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/ProjectStormtrooper/ProjectStormtrooper/CollectionGenericObjects/MassiveGenericObjects.cs @@ -57,9 +57,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 DrawningBaseStormtrooper, item as DrawningBaseStormtrooper)) + throw new ObjectIsEqualException(); + } + } int index = 0; while (index < _collection.Length) { @@ -73,10 +81,18 @@ public class MassiveGenericObjects : ICollectionGenericObjects throw new CollectionOverflowException(Count); } - public int Insert(T obj, int position) + public int Insert(T obj, int position, IEqualityComparer? comparer = null) { // TODO выброс ошибки если переполнение // TODO выброс ошибки если выход за границу + if (comparer != null) + { + foreach (T? item in _collection) + { + if ((comparer as IEqualityComparer).Equals(obj as DrawningBaseStormtrooper, item as DrawningBaseStormtrooper)) + throw new ObjectIsEqualException(); + } + } if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position); if (_collection[position] == null) { @@ -124,4 +140,8 @@ public class MassiveGenericObjects : ICollectionGenericObjects yield return _collection[i]; } } + void ICollectionGenericObjects.CollectionSort(IComparer comparer) + { + Array.Sort(_collection, comparer); + } } diff --git a/ProjectStormtrooper/ProjectStormtrooper/CollectionGenericObjects/StorageCollection.cs b/ProjectStormtrooper/ProjectStormtrooper/CollectionGenericObjects/StorageCollection.cs index 55003ca..3e9c068 100644 --- a/ProjectStormtrooper/ProjectStormtrooper/CollectionGenericObjects/StorageCollection.cs +++ b/ProjectStormtrooper/ProjectStormtrooper/CollectionGenericObjects/StorageCollection.cs @@ -14,17 +14,17 @@ where T : DrawningBaseStormtrooper /// /// Словарь (хранилище) с коллекциями /// - readonly Dictionary> _storages; + readonly Dictionary> _storages; /// /// Возвращение списка названий коллекций /// - public List Keys => _storages.Keys.ToList(); + public List Keys => _storages.Keys.ToList(); /// /// Конструктор /// public StorageCollection() { - _storages = new Dictionary>(); + _storages = new Dictionary>(); } /// /// Добавление коллекции в хранилище @@ -35,14 +35,16 @@ where T : DrawningBaseStormtrooper { // TODO проверка, что name не пустой и нет в словаре записи с таким ключом // TODO Прописать логику для добавления - if (!(collectionType == CollectionType.None) && !_storages.ContainsKey(name)) { + CollectionInfo collectionInfo = new CollectionInfo(name, collectionType, string.Empty); + if (_storages.ContainsKey(collectionInfo)) return; + if (!(collectionType == CollectionType.None) && !_storages.ContainsKey(collectionInfo)) { if (collectionType == CollectionType.List) { - _storages.Add(name, new ListGenericObjects()); + _storages.Add(collectionInfo, new ListGenericObjects()); } else if (collectionType == CollectionType.Massive) { - _storages.Add(name, new MassiveGenericObjects()); + _storages.Add(collectionInfo, new MassiveGenericObjects()); } } } @@ -53,7 +55,8 @@ where T : DrawningBaseStormtrooper 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); } /// /// Доступ к коллекции @@ -65,10 +68,8 @@ where T : DrawningBaseStormtrooper get { // TODO Продумать логику получения объекта - if (_storages.ContainsKey(name)) - { - return _storages[name]; - } + CollectionInfo collectionInfo = new CollectionInfo(name, CollectionType.None, string.Empty); + if (_storages.ContainsKey(collectionInfo)) return _storages[collectionInfo]; return null; } } @@ -104,7 +105,7 @@ where T : DrawningBaseStormtrooper using (StreamWriter writer = new StreamWriter(filename)) { writer.Write(_collectionKey); - foreach (KeyValuePair> value in _storages) + foreach (KeyValuePair> value in _storages) { writer.Write(Environment.NewLine); if (value.Value.Count == 0) @@ -113,8 +114,6 @@ where T : DrawningBaseStormtrooper } writer.Write(value.Key); writer.Write(_separatorForKeyValue); - writer.Write(value.Value.GetCollectionType); - writer.Write(_separatorForKeyValue); writer.Write(value.Value.MaxCount); writer.Write(_separatorForKeyValue); foreach (T? item in value.Value.GetItems()) @@ -157,18 +156,18 @@ where T : DrawningBaseStormtrooper while ((strs = fs.ReadLine()) != null) { string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); - if (record.Length != 4) + if (record.Length != 3) { continue; } - CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]); - ICollectionGenericObjects? 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("Не удалось создать коллекцию"); } - collection.MaxCount = Convert.ToInt32(record[2]); - string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); + collection.MaxCount = Convert.ToInt32(record[1]); + string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); foreach (string elem in set) { if (elem?.CreateDrawningStormtrooper() is T stormtrooper) @@ -186,7 +185,7 @@ where T : DrawningBaseStormtrooper } } } - _storages.Add(record[0], collection); + _storages.Add(collectionInfo, collection); } } } diff --git a/ProjectStormtrooper/ProjectStormtrooper/Drawnings/DrawingBaseStormtrooperCompareByColor.cs b/ProjectStormtrooper/ProjectStormtrooper/Drawnings/DrawingBaseStormtrooperCompareByColor.cs new file mode 100644 index 0000000..7095996 --- /dev/null +++ b/ProjectStormtrooper/ProjectStormtrooper/Drawnings/DrawingBaseStormtrooperCompareByColor.cs @@ -0,0 +1,28 @@ +namespace ProjectStormtrooper.Drawnings; + +public class DrawingBaseStormtrooperCompareByColor : IComparer +{ + public int Compare(DrawningBaseStormtrooper? x, DrawningBaseStormtrooper? y) + { + if (x == null || x.EntityBaseStormtrooper == null) + { + return 1; + } + + if (y == null || y.EntityBaseStormtrooper == null) + { + return -1; + } + var bodycolorCompare = x.EntityBaseStormtrooper.BodyColor.Name.CompareTo(y.EntityBaseStormtrooper.BodyColor.Name); + if (bodycolorCompare != 0) + { + return bodycolorCompare; + } + var speedCompare = x.EntityBaseStormtrooper.Speed.CompareTo(y.EntityBaseStormtrooper.Speed); + if (speedCompare != 0) + { + return speedCompare; + } + return x.EntityBaseStormtrooper.Weight.CompareTo(y.EntityBaseStormtrooper.Weight); + } +} diff --git a/ProjectStormtrooper/ProjectStormtrooper/Drawnings/DrawingBaseStormtrooperCompareByType.cs b/ProjectStormtrooper/ProjectStormtrooper/Drawnings/DrawingBaseStormtrooperCompareByType.cs new file mode 100644 index 0000000..3cac600 --- /dev/null +++ b/ProjectStormtrooper/ProjectStormtrooper/Drawnings/DrawingBaseStormtrooperCompareByType.cs @@ -0,0 +1,35 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectStormtrooper.Drawnings; + +public class DrawingBaseStormtrooperCompareByType : IComparer +{ + public int Compare(DrawningBaseStormtrooper? x, DrawningBaseStormtrooper? y) + { + if (x == null || x.EntityBaseStormtrooper == null) + { + return 1; + } + + if (y == null || y.EntityBaseStormtrooper == null) + { + return -1; + } + + if (x.GetType().Name != y.GetType().Name) + { + return x.GetType().Name.CompareTo(y.GetType().Name); + } + + var speedCompare = x.EntityBaseStormtrooper.Speed.CompareTo(y.EntityBaseStormtrooper.Speed); + if (speedCompare != 0) + { + return speedCompare; + } + return x.EntityBaseStormtrooper.Weight.CompareTo(y.EntityBaseStormtrooper.Weight); + } +} diff --git a/ProjectStormtrooper/ProjectStormtrooper/Drawnings/DrawingBaseStormtrooperEqutables.cs b/ProjectStormtrooper/ProjectStormtrooper/Drawnings/DrawingBaseStormtrooperEqutables.cs new file mode 100644 index 0000000..8e8f00e --- /dev/null +++ b/ProjectStormtrooper/ProjectStormtrooper/Drawnings/DrawingBaseStormtrooperEqutables.cs @@ -0,0 +1,57 @@ +using ProjectStormtrooper.Entities; +using System.Diagnostics.CodeAnalysis; + +namespace ProjectStormtrooper.Drawnings; + +public class DrawingBaseStormtrooperEqutables : IEqualityComparer +{ + public bool Equals(DrawningBaseStormtrooper? x, DrawningBaseStormtrooper? y) + { + if (x == null || x.EntityBaseStormtrooper == null) + { + return false; + } + if (y == null || y.EntityBaseStormtrooper == null) + { + return false; + } + if (x.GetType().Name != y.GetType().Name) + { + return false; + } + if (x.EntityBaseStormtrooper.Speed != y.EntityBaseStormtrooper.Speed) + { + return false; + } + if (x.EntityBaseStormtrooper.Weight != y.EntityBaseStormtrooper.Weight) + { + return false; + } + if (x.EntityBaseStormtrooper.BodyColor != y.EntityBaseStormtrooper.BodyColor) + { + return false; + } + if (x is DrawingStormtrooper && y is DrawingStormtrooper) + { + EntityStormtrooper _x = (EntityStormtrooper)x.EntityBaseStormtrooper; + EntityStormtrooper _y = (EntityStormtrooper)x.EntityBaseStormtrooper; + if (_x.AdditionalColor != _y.AdditionalColor) + { + return false; + } + if (_x.Rockets != _y.Rockets) + { + return false; + } + if (_x.Bombs != _y.Bombs) + { + return false; + } + } + return true; + } + public int GetHashCode([DisallowNull] DrawningBaseStormtrooper obj) + { + return obj.GetHashCode(); + } +} diff --git a/ProjectStormtrooper/ProjectStormtrooper/Exceptions/ObjectIsEqualException.cs b/ProjectStormtrooper/ProjectStormtrooper/Exceptions/ObjectIsEqualException.cs new file mode 100644 index 0000000..b08df89 --- /dev/null +++ b/ProjectStormtrooper/ProjectStormtrooper/Exceptions/ObjectIsEqualException.cs @@ -0,0 +1,14 @@ + + +using System.Runtime.Serialization; + +namespace ProjectStormtrooper.Exceptions; + +public class ObjectIsEqualException : ApplicationException +{ + public ObjectIsEqualException(int count) : base("В коллекции содержится равный элемент: " + count) { } + public ObjectIsEqualException() : base() { } + public ObjectIsEqualException(string message) : base(message) { } + public ObjectIsEqualException(string message, Exception exception) : base(message, exception) { } + protected ObjectIsEqualException(SerializationInfo info, StreamingContext contex) : base(info, contex) { } +} diff --git a/ProjectStormtrooper/ProjectStormtrooper/FormStormtrooperCollection.Designer.cs b/ProjectStormtrooper/ProjectStormtrooper/FormStormtrooperCollection.Designer.cs index 4467095..e585485 100644 --- a/ProjectStormtrooper/ProjectStormtrooper/FormStormtrooperCollection.Designer.cs +++ b/ProjectStormtrooper/ProjectStormtrooper/FormStormtrooperCollection.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(); @@ -74,6 +76,8 @@ // // panelCompanyTools // + panelCompanyTools.Controls.Add(buttonSortByColor); + panelCompanyTools.Controls.Add(buttonSortByType); panelCompanyTools.Controls.Add(buttonCreateCompany); panelCompanyTools.Controls.Add(buttonAddStormtrooper); panelCompanyTools.Controls.Add(buttonRefresh); @@ -82,9 +86,9 @@ panelCompanyTools.Controls.Add(buttonRemoveStormtrooper); panelCompanyTools.Dock = DockStyle.Bottom; panelCompanyTools.Enabled = false; - panelCompanyTools.Location = new Point(3, 294); + panelCompanyTools.Location = new Point(3, 269); panelCompanyTools.Name = "panelCompanyTools"; - panelCompanyTools.Size = new Size(219, 357); + panelCompanyTools.Size = new Size(219, 382); panelCompanyTools.TabIndex = 8; // // buttonCreateCompany @@ -109,7 +113,7 @@ // // buttonRefresh // - buttonRefresh.Location = new Point(3, 293); + buttonRefresh.Location = new Point(6, 235); buttonRefresh.Name = "buttonRefresh"; buttonRefresh.Size = new Size(213, 52); buttonRefresh.TabIndex = 6; @@ -119,7 +123,7 @@ // // maskedTextBoxPosition // - maskedTextBoxPosition.Location = new Point(3, 148); + maskedTextBoxPosition.Location = new Point(3, 90); maskedTextBoxPosition.Mask = "00"; maskedTextBoxPosition.Name = "maskedTextBoxPosition"; maskedTextBoxPosition.Size = new Size(213, 23); @@ -128,7 +132,7 @@ // // buttonGoToCheck // - buttonGoToCheck.Location = new Point(3, 235); + buttonGoToCheck.Location = new Point(3, 177); buttonGoToCheck.Name = "buttonGoToCheck"; buttonGoToCheck.Size = new Size(213, 52); buttonGoToCheck.TabIndex = 5; @@ -138,7 +142,7 @@ // // buttonRemoveStormtrooper // - buttonRemoveStormtrooper.Location = new Point(3, 177); + buttonRemoveStormtrooper.Location = new Point(3, 119); buttonRemoveStormtrooper.Name = "buttonRemoveStormtrooper"; buttonRemoveStormtrooper.Size = new Size(213, 52); buttonRemoveStormtrooper.TabIndex = 4; @@ -158,12 +162,12 @@ panelStorage.Dock = DockStyle.Top; panelStorage.Location = new Point(3, 19); panelStorage.Name = "panelStorage"; - panelStorage.Size = new Size(219, 242); + panelStorage.Size = new Size(219, 215); panelStorage.TabIndex = 7; // // buttonCollectionDel // - buttonCollectionDel.Location = new Point(3, 211); + buttonCollectionDel.Location = new Point(3, 181); buttonCollectionDel.Name = "buttonCollectionDel"; buttonCollectionDel.Size = new Size(213, 23); buttonCollectionDel.TabIndex = 6; @@ -177,7 +181,7 @@ listBoxCollection.ItemHeight = 15; listBoxCollection.Location = new Point(3, 111); listBoxCollection.Name = "listBoxCollection"; - listBoxCollection.Size = new Size(213, 94); + listBoxCollection.Size = new Size(213, 64); listBoxCollection.TabIndex = 5; // // buttonCollectionAdd @@ -234,7 +238,7 @@ comboBoxSelectorCompany.DropDownStyle = ComboBoxStyle.DropDownList; comboBoxSelectorCompany.FormattingEnabled = true; comboBoxSelectorCompany.Items.AddRange(new object[] { "Хранилище" }); - comboBoxSelectorCompany.Location = new Point(6, 267); + comboBoxSelectorCompany.Location = new Point(6, 240); comboBoxSelectorCompany.Name = "comboBoxSelectorCompany"; comboBoxSelectorCompany.Size = new Size(213, 23); comboBoxSelectorCompany.TabIndex = 0; @@ -290,6 +294,26 @@ openFileDialog.FileName = "openFileDialog1"; openFileDialog.Filter = "txt file | *.txt"; // + // buttonSortByColor + // + buttonSortByColor.Location = new Point(6, 344); + buttonSortByColor.Name = "buttonSortByColor"; + buttonSortByColor.Size = new Size(213, 29); + buttonSortByColor.TabIndex = 9; + buttonSortByColor.Text = "Сортировка по цвету"; + buttonSortByColor.UseVisualStyleBackColor = true; + buttonSortByColor.Click += buttonSortByColor_Click; + // + // buttonSortByType + // + buttonSortByType.Location = new Point(6, 309); + buttonSortByType.Name = "buttonSortByType"; + buttonSortByType.Size = new Size(213, 29); + buttonSortByType.TabIndex = 8; + buttonSortByType.Text = "Сортировка по типу"; + buttonSortByType.UseVisualStyleBackColor = true; + buttonSortByType.Click += buttonSortByType_Click; + // // FormStormtrooperCollection // AutoScaleDimensions = new SizeF(7F, 15F); @@ -339,5 +363,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/ProjectStormtrooper/ProjectStormtrooper/FormStormtrooperCollection.cs b/ProjectStormtrooper/ProjectStormtrooper/FormStormtrooperCollection.cs index 4018f1b..901a85a 100644 --- a/ProjectStormtrooper/ProjectStormtrooper/FormStormtrooperCollection.cs +++ b/ProjectStormtrooper/ProjectStormtrooper/FormStormtrooperCollection.cs @@ -64,9 +64,14 @@ public partial class FormStormtrooperCollection : Form MessageBox.Show("Не удалось добавить объект"); _logger.LogError("Ошибка: {Message}", ex.Message); } + catch (ObjectIsEqualException ex) + { + MessageBox.Show("Не удалось добавить объект"); + _logger.LogError("Ошибка: {Message}", ex.Message); + } } - + /// /// Добавление бомбардировщика /// @@ -98,7 +103,7 @@ public partial class FormStormtrooperCollection : Form int pos = Convert.ToInt32(maskedTextBoxPosition.Text); int tempSize = StormtrooperSharingService.getAmountOfObjects(); - try + try { if (_company - pos != null) { @@ -107,12 +112,12 @@ public partial class FormStormtrooperCollection : Form _logger.LogInformation("Удален объект по позиции " + pos); } } - catch(Exception ex) + catch (Exception ex) { MessageBox.Show("Не удалось удалить объект"); _logger.LogError("Ошибка: {Message}", ex.Message); } - + } /// @@ -194,7 +199,7 @@ public partial class FormStormtrooperCollection : Form RerfreshListBoxItems(); _logger.LogInformation("Коллекция добавлена " + textBoxCollectionName.Text); } - catch(Exception ex) + catch (Exception ex) { _logger.LogError("Ошибка: {Message}", ex.Message); } @@ -268,7 +273,7 @@ public partial class FormStormtrooperCollection : 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); @@ -316,7 +321,7 @@ public partial class FormStormtrooperCollection : Form RerfreshListBoxItems(); _logger.LogInformation("Загрузка из файла: {filename}", openFileDialog.FileName); } - catch(Exception ex) + catch (Exception ex) { MessageBox.Show("Загрузка не удалась", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); @@ -325,6 +330,28 @@ public partial class FormStormtrooperCollection : Form } } + + private void buttonSortByType_Click(object sender, EventArgs e) + { + CompareStormtrooper(new DrawingBaseStormtrooperCompareByType()); + } + + private void buttonSortByColor_Click(object sender, EventArgs e) + { + CompareStormtrooper(new DrawingBaseStormtrooperCompareByColor()); + } + + private void CompareStormtrooper(IComparer comparer) + { + if (_company == null) + { + return; + } + _company.Sort(comparer); + pictureBox.Image = _company.Show(); + } + + }