From 2cc8137a2d45afd141009d66692855bdf72b2b7e Mon Sep 17 00:00:00 2001 From: Anastasia-Sin Date: Tue, 14 May 2024 23:17:44 +0400 Subject: [PATCH] =?UTF-8?q?8=20=D0=BB=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?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../AbstractCompany.cs | 9 ++- .../CollectionInfo.cs | 75 +++++++++++++++++++ .../ICollectionGenericObjects.cs | 15 +++- .../ListGenericObjects.cs | 30 +++++++- .../MassiveGenericObjects.cs | 38 +++++++--- .../StorageCollection.cs | 72 +++++++++++------- .../Drawnings/DrawiningCruiserEqutables.cs | 54 +++++++++++++ .../DrawningCruiserCompareByColor.cs | 34 +++++++++ .../Drawnings/DrawningCruiserCompareByType.cs | 35 +++++++++ .../ObjectAlreadyInCollectionException.cs | 22 ++++++ .../FormCruisersCollection.Designer.cs | 42 +++++++++-- ProjectCruiser/FormCruisersCollection.cs | 59 +++++++++++---- 12 files changed, 417 insertions(+), 68 deletions(-) create mode 100644 ProjectCruiser/CollectionGenericObjects/CollectionInfo.cs create mode 100644 ProjectCruiser/Drawnings/DrawiningCruiserEqutables.cs create mode 100644 ProjectCruiser/Drawnings/DrawningCruiserCompareByColor.cs create mode 100644 ProjectCruiser/Drawnings/DrawningCruiserCompareByType.cs create mode 100644 ProjectCruiser/Exceptions/ObjectAlreadyInCollectionException.cs diff --git a/ProjectCruiser/CollectionGenericObjects/AbstractCompany.cs b/ProjectCruiser/CollectionGenericObjects/AbstractCompany.cs index 079c3fa..5993b78 100644 --- a/ProjectCruiser/CollectionGenericObjects/AbstractCompany.cs +++ b/ProjectCruiser/CollectionGenericObjects/AbstractCompany.cs @@ -61,7 +61,7 @@ namespace ProjectCruiser.CollectionGenericObjects /// public static int operator +(AbstractCompany company, DrawningCruiser сruiser) { - return company._collection.Insert(сruiser); + return company._collection.Insert(сruiser, new DrawiningCruiserEqutables()); } /// @@ -109,6 +109,13 @@ namespace ProjectCruiser.CollectionGenericObjects } return bitmap; } + + /// + /// Сортировка + /// + /// Сравнитель объектов + public void Sort(IComparer comparer) => _collection?.CollectionSort(comparer); + /// /// Вывод заднего фона /// diff --git a/ProjectCruiser/CollectionGenericObjects/CollectionInfo.cs b/ProjectCruiser/CollectionGenericObjects/CollectionInfo.cs new file mode 100644 index 0000000..c4f5a0f --- /dev/null +++ b/ProjectCruiser/CollectionGenericObjects/CollectionInfo.cs @@ -0,0 +1,75 @@ +namespace ProjectCruiser.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/ProjectCruiser/CollectionGenericObjects/ICollectionGenericObjects.cs b/ProjectCruiser/CollectionGenericObjects/ICollectionGenericObjects.cs index d92a50c..1f9089c 100644 --- a/ProjectCruiser/CollectionGenericObjects/ICollectionGenericObjects.cs +++ b/ProjectCruiser/CollectionGenericObjects/ICollectionGenericObjects.cs @@ -1,4 +1,6 @@ -namespace ProjectCruiser.CollectionGenericObjects +using ProjectCruiser.Drawnings; + +namespace ProjectCruiser.CollectionGenericObjects { /// /// Интерфейс описания действий для набора хранимых объектов @@ -21,8 +23,9 @@ /// Добавление объекта в коллекцию /// /// Добавляемый объект + /// /// Cравнение двух объектов /// true - вставка прошла удачно, false - вставка не удалась - int Insert(T obj); + int Insert(T obj, IEqualityComparer? comparer = null); /// /// Добавление объекта в коллекцию на конкретную позицию @@ -30,7 +33,7 @@ /// Добавляемый объект /// Позиция /// true - вставка прошла удачно, false - вставка не удалась - int Insert(T obj, int position); + int Insert(T obj, int position, IEqualityComparer? comparer = null); /// /// Удаление объекта из коллекции с конкретной позиции @@ -56,6 +59,12 @@ /// Поэлементый вывод элементов коллекции IEnumerable GetItems(); + /// + /// Сортировка коллекции + /// + /// Сравнитель объектов + void CollectionSort(IComparer comparer); + } } diff --git a/ProjectCruiser/CollectionGenericObjects/ListGenericObjects.cs b/ProjectCruiser/CollectionGenericObjects/ListGenericObjects.cs index b905497..b0c5976 100644 --- a/ProjectCruiser/CollectionGenericObjects/ListGenericObjects.cs +++ b/ProjectCruiser/CollectionGenericObjects/ListGenericObjects.cs @@ -1,4 +1,5 @@ -using ProjectCruiser.Exceptions; +using ProjectCruiser.Drawnings; +using ProjectCruiser.Exceptions; namespace ProjectCruiser.CollectionGenericObjects { @@ -47,23 +48,38 @@ namespace ProjectCruiser.CollectionGenericObjects return _collection[position]; } - public int Insert(T obj) + public int Insert(T obj, IEqualityComparer? comparer = null) { // TODO проверка, что не превышено максимальное количество элементов // TODO выбром позиций, если переполнение + // TODO выброc позиций, если такой объект есть в коллекции // TODO вставка в конец набора + for (int i = 0; i < Count; i++) + { + if (comparer.Equals((_collection[i] as DrawningCruiser), (obj as DrawningCruiser))) throw new ObjectAlreadyInCollectionException(i); + } + 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 выброc позиций, если такой объект есть в коллекции // TODO проверка позиции // TODO вставка по позиции + for (int i = 0; i < Count; i++) + { + if (comparer.Equals((_collection[i] as DrawningCruiser), (obj as DrawningCruiser))) throw new ObjectAlreadyInCollectionException(i); + } + if (Count == _maxCount) throw new CollectionOverflowException(Count); + if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position); + _collection.Insert(position, obj); return position; @@ -72,9 +88,10 @@ namespace ProjectCruiser.CollectionGenericObjects public T Remove(int position) { // TODO проверка позиции - // TODO удаление объекта из списка // TODO выбром позиций, если выход за границы массива + // TODO удаление объекта из списка if (position >= _collection.Count || position < 0) throw new PositionOutOfCollectionException(position); + T obj = _collection[position]; _collection.RemoveAt(position); return obj; @@ -87,5 +104,10 @@ namespace ProjectCruiser.CollectionGenericObjects yield return _collection[i]; } } + + public void CollectionSort(IComparer comparer) + { + _collection.Sort(comparer); + } } } diff --git a/ProjectCruiser/CollectionGenericObjects/MassiveGenericObjects.cs b/ProjectCruiser/CollectionGenericObjects/MassiveGenericObjects.cs index b428c38..427e15b 100644 --- a/ProjectCruiser/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/ProjectCruiser/CollectionGenericObjects/MassiveGenericObjects.cs @@ -1,4 +1,5 @@ -using ProjectCruiser.Exceptions; +using ProjectCruiser.Drawnings; +using ProjectCruiser.Exceptions; namespace ProjectCruiser.CollectionGenericObjects { @@ -55,34 +56,44 @@ namespace ProjectCruiser.CollectionGenericObjects return _collection[position]; } - public int Insert(T obj) + public int Insert(T obj, IEqualityComparer? comparer = null) { // TODO вставка в свободное место набора // TODO выброc позиций, если переполнение - int index = 0; - while (index < Count && _collection[index] != null) + // TODO выброc позиций, если такой объект есть в коллекции + for (int i = 0; i < Count; i++) { - index++; + if (comparer.Equals((_collection[i] as DrawningCruiser), (obj as DrawningCruiser))) throw new ObjectAlreadyInCollectionException(i); } - if (index < Count) + for (int i = 0; i < Count; i++) { - _collection[index] = obj; - return index; + if (_collection[i] == null) + { + _collection[i] = obj; + return i; + } } throw new CollectionOverflowException(Count); } - public int Insert(T obj, int position) + public int Insert(T obj, int position, IEqualityComparer? comparer = null) { + // TODO выброc позиций, если такой объект есть в коллекции // TODO проверка позиции + // TODO выбром позиций, если выход за границы массива // TODO проверка, что элемент массива по этой позиции пустой, если нет, то // ищется свободное место после этой позиции и идет вставка туда // если нет после, ищем до - // TODO вставка // TODO выбром позиций, если переполнение - // TODO выбром позиций, если выход за границы массива + // TODO вставка + for (int i = 0; i < Count; i++) + { + if (comparer.Equals((_collection[i] as DrawningCruiser), (obj as DrawningCruiser))) throw new ObjectAlreadyInCollectionException(i); + + } + if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position); if (_collection[position] != null) @@ -143,5 +154,10 @@ namespace ProjectCruiser.CollectionGenericObjects yield return _collection[i]; } } + + public void CollectionSort(IComparer comparer) + { + Array.Sort(_collection, comparer); + } } } diff --git a/ProjectCruiser/CollectionGenericObjects/StorageCollection.cs b/ProjectCruiser/CollectionGenericObjects/StorageCollection.cs index 799e711..972cfe6 100644 --- a/ProjectCruiser/CollectionGenericObjects/StorageCollection.cs +++ b/ProjectCruiser/CollectionGenericObjects/StorageCollection.cs @@ -13,12 +13,12 @@ namespace ProjectCruiser.CollectionGenericObjects /// /// Словарь (хранилище) с коллекциями /// - readonly Dictionary> _storages; + readonly Dictionary> _storages; /// /// Возвращение списка названий коллекций /// - public List Keys => _storages.Keys.ToList(); + public List Keys => _storages.Keys.ToList(); /// /// Ключевое слово, с которого должен начинаться файл @@ -40,7 +40,7 @@ namespace ProjectCruiser.CollectionGenericObjects /// public StorageCollection() { - _storages = new Dictionary>(); + _storages = new Dictionary>(); } /// @@ -48,29 +48,40 @@ namespace ProjectCruiser.CollectionGenericObjects /// /// Название коллекции /// тип коллекции - public void AddCollection(string name, CollectionType collectionType) + public void AddCollection(CollectionInfo name) { // TODO проверка, что name не пустой и нет в словаре записи с таким ключом // TODO Прописать логику для добавления - if (_storages.ContainsKey(name)) return; + if (name == null || _storages.ContainsKey(name)) + { + return; + } - if (collectionType == CollectionType.None) return; - else if (collectionType == CollectionType.Massive) - _storages[name] = new MassiveGenericObjects(); - else if (collectionType == CollectionType.List) - _storages[name] = new ListGenericObjects(); + if (name.CollectionType == CollectionType.Massive) + { + _storages.Add(name, new MassiveGenericObjects()); + } + + if (name.CollectionType == CollectionType.List) + { + _storages.Add(name, new ListGenericObjects()); + } } /// /// Удаление коллекции /// /// Название коллекции - public void DelCollection(string name) + public void DelCollection(CollectionInfo name) { // TODO Прописать логику для удаления коллекции - if (_storages.ContainsKey(name)) - _storages.Remove(name); + if (name == null || !_storages.ContainsKey(name)) + { + return; + } + + _storages.Remove(name); } /// @@ -78,13 +89,16 @@ namespace ProjectCruiser.CollectionGenericObjects /// /// Название коллекции /// - public ICollectionGenericObjects? this[string name] + public ICollectionGenericObjects? this[CollectionInfo name] { get { // TODO Продумать логику получения объекта if (_storages.ContainsKey(name)) + { return _storages[name]; + } + return null; } } @@ -111,7 +125,7 @@ namespace ProjectCruiser.CollectionGenericObjects using StreamWriter streamWriter = new StreamWriter(fs); streamWriter.Write(_collectionKey); - foreach (KeyValuePair> value in _storages) + foreach (KeyValuePair> value in _storages) { streamWriter.Write(Environment.NewLine); @@ -122,8 +136,6 @@ namespace ProjectCruiser.CollectionGenericObjects streamWriter.Write(value.Key); streamWriter.Write(_separatorForKeyValue); - streamWriter.Write(value.Value.GetCollectionType); - streamWriter.Write(_separatorForKeyValue); streamWriter.Write(value.Value.MaxCount); streamWriter.Write(_separatorForKeyValue); @@ -164,27 +176,25 @@ namespace ProjectCruiser.CollectionGenericObjects 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("Не удалось определить тип коллекции:" + record[1]); - } - collection.MaxCount = Convert.ToInt32(record[2]); + CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(record[0]) ?? + throw new Exception("Не удалось определить информацию коллекции: " + record[0]); + ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionInfo.CollectionType) ?? + throw new Exception("Не удалось создать коллекцию"); + 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?.CreateDrawningCruiser() is T aircraft) + if (elem?.CreateDrawningCruiser() is T cruiser) { try { - if (collection.Insert(aircraft) == -1) + if (collection.Insert(cruiser, new DrawiningCruiserEqutables()) == -1) { throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]); } @@ -193,9 +203,13 @@ namespace ProjectCruiser.CollectionGenericObjects { throw new CollectionOverflowException("Коллекция переполнена", ex); } + catch (ObjectAlreadyInCollectionException ex) + { + throw new InvalidOperationException("Объект уже присутствует в коллекции", ex); + } } } - _storages.Add(record[0], collection); + _storages.Add(collectionInfo, collection); } } } diff --git a/ProjectCruiser/Drawnings/DrawiningCruiserEqutables.cs b/ProjectCruiser/Drawnings/DrawiningCruiserEqutables.cs new file mode 100644 index 0000000..a6a1112 --- /dev/null +++ b/ProjectCruiser/Drawnings/DrawiningCruiserEqutables.cs @@ -0,0 +1,54 @@ +using System.Diagnostics.CodeAnalysis; + +namespace ProjectCruiser.Drawnings; + +/// +/// Реализация сравнения двух объектов класса-прорисовки +/// +public class DrawiningCruiserEqutables : IEqualityComparer +{ + public bool Equals(DrawningCruiser? x, DrawningCruiser? y) + { + if (x == null || x.EntityCruiser == null) + { + return false; + } + + if (y == null || y.EntityCruiser == null) + { + return false; + } + + if (x.GetType().Name != y.GetType().Name) + { + return false; + } + + if (x.EntityCruiser.Speed != y.EntityCruiser.Speed) + { + return false; + } + + if (x.EntityCruiser.Weight != y.EntityCruiser.Weight) + { + return false; + } + + if (x.EntityCruiser.BodyColor != y.EntityCruiser.BodyColor) + { + return false; + } + + if (x is DrawningMilitaryCruiser && y is DrawningMilitaryCruiser) + { + // TODO доделать логику сравнения дополнительных параметров + } + + return true; + } + + public int GetHashCode([DisallowNull] DrawningCruiser obj) + { + return obj.GetHashCode(); + } +} diff --git a/ProjectCruiser/Drawnings/DrawningCruiserCompareByColor.cs b/ProjectCruiser/Drawnings/DrawningCruiserCompareByColor.cs new file mode 100644 index 0000000..7651bd1 --- /dev/null +++ b/ProjectCruiser/Drawnings/DrawningCruiserCompareByColor.cs @@ -0,0 +1,34 @@ +using ProjectCruiser.Entities; + +namespace ProjectCruiser.Drawnings; + +/// +/// Сравнение по цвету, скорости, весу +/// +public class DrawningCruiserCompareByColor : IComparer +{ + public int Compare(DrawningCruiser? x, DrawningCruiser? y) + { + // TODO прописать логику сравения по цветам, скорости, весу + if (x == null || x.EntityCruiser == null) + { + return 1; + } + + if (y == null || y.EntityCruiser == null) + { + return -1; + } + var bodycolorCompare = x.EntityCruiser.BodyColor.Name.CompareTo(y.EntityCruiser.BodyColor.Name); + if (bodycolorCompare != 0) + { + return bodycolorCompare; + } + var speedCompare = x.EntityCruiser.Speed.CompareTo(y.EntityCruiser.Speed); + if (speedCompare != 0) + { + return speedCompare; + } + return x.EntityCruiser.Weight.CompareTo(y.EntityCruiser.Weight); + } +} diff --git a/ProjectCruiser/Drawnings/DrawningCruiserCompareByType.cs b/ProjectCruiser/Drawnings/DrawningCruiserCompareByType.cs new file mode 100644 index 0000000..28cb5de --- /dev/null +++ b/ProjectCruiser/Drawnings/DrawningCruiserCompareByType.cs @@ -0,0 +1,35 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectCruiser.Drawnings; + +/// +/// Сравнение по типу, скорости, весу +/// +public class DrawningCruiserCompareByType : IComparer +{ + public int Compare(DrawningCruiser? x, DrawningCruiser? y) + { + if (x == null || x.EntityCruiser == null) + { + return 1; + } + if (y == null || y.EntityCruiser == null) + { + return -1; + } + if (x.GetType().Name != y.GetType().Name) + { + return x.GetType().Name.CompareTo(y.GetType().Name); + } + var speedCompare = x.EntityCruiser.Speed.CompareTo(y.EntityCruiser.Speed); + if (speedCompare != 0) + { + return speedCompare; + } + return x.EntityCruiser.Weight.CompareTo(y.EntityCruiser.Weight); + } +} diff --git a/ProjectCruiser/Exceptions/ObjectAlreadyInCollectionException.cs b/ProjectCruiser/Exceptions/ObjectAlreadyInCollectionException.cs new file mode 100644 index 0000000..9dc2cc4 --- /dev/null +++ b/ProjectCruiser/Exceptions/ObjectAlreadyInCollectionException.cs @@ -0,0 +1,22 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectCruiser.Exceptions; + +[Serializable] +internal class ObjectAlreadyInCollectionException : ApplicationException +{ + public ObjectAlreadyInCollectionException(int index) : base("Такой объект уже присутствует в коллекции. Позиция " + index) { } + + public ObjectAlreadyInCollectionException() : base() { } + + public ObjectAlreadyInCollectionException(string message) : base(message) { } + + public ObjectAlreadyInCollectionException(string message, Exception exception) : base(message, exception) { } + + protected ObjectAlreadyInCollectionException(SerializationInfo info, StreamingContext contex) : base(info, contex) { } +} diff --git a/ProjectCruiser/FormCruisersCollection.Designer.cs b/ProjectCruiser/FormCruisersCollection.Designer.cs index 21dab30..3269420 100644 --- a/ProjectCruiser/FormCruisersCollection.Designer.cs +++ b/ProjectCruiser/FormCruisersCollection.Designer.cs @@ -52,6 +52,8 @@ loadToolStripMenuItem = new ToolStripMenuItem(); saveFileDialog = new SaveFileDialog(); openFileDialog = new OpenFileDialog(); + buttonSortByColor = new Button(); + buttonSortByType = new Button(); groupBoxTools.SuspendLayout(); panelStorage.SuspendLayout(); panelCompanyTools.SuspendLayout(); @@ -178,6 +180,8 @@ // // panelCompanyTools // + panelCompanyTools.Controls.Add(buttonSortByColor); + panelCompanyTools.Controls.Add(buttonSortByType); panelCompanyTools.Controls.Add(ButtonAddCruiser); panelCompanyTools.Controls.Add(buttonRefresh); panelCompanyTools.Controls.Add(ButtonRemoveCruiser); @@ -204,9 +208,9 @@ // buttonRefresh // buttonRefresh.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; - buttonRefresh.Location = new Point(18, 227); + buttonRefresh.Location = new Point(19, 149); buttonRefresh.Name = "buttonRefresh"; - buttonRefresh.Size = new Size(186, 41); + buttonRefresh.Size = new Size(186, 29); buttonRefresh.TabIndex = 5; buttonRefresh.Text = "обновить"; buttonRefresh.UseVisualStyleBackColor = true; @@ -215,9 +219,9 @@ // ButtonRemoveCruiser // ButtonRemoveCruiser.Anchor = AnchorStyles.Right; - ButtonRemoveCruiser.Location = new Point(18, 138); + ButtonRemoveCruiser.Location = new Point(19, 82); ButtonRemoveCruiser.Name = "ButtonRemoveCruiser"; - ButtonRemoveCruiser.Size = new Size(186, 40); + ButtonRemoveCruiser.Size = new Size(186, 28); ButtonRemoveCruiser.TabIndex = 3; ButtonRemoveCruiser.Text = "удалить крейсер"; ButtonRemoveCruiser.UseVisualStyleBackColor = true; @@ -225,7 +229,7 @@ // // maskedTextBoxPosision // - maskedTextBoxPosision.Location = new Point(17, 105); + maskedTextBoxPosision.Location = new Point(18, 49); maskedTextBoxPosision.Mask = "00"; maskedTextBoxPosision.Name = "maskedTextBoxPosision"; maskedTextBoxPosision.Size = new Size(187, 27); @@ -235,9 +239,9 @@ // buttonGetToTest // buttonGetToTest.Anchor = AnchorStyles.Right; - buttonGetToTest.Location = new Point(18, 184); + buttonGetToTest.Location = new Point(19, 116); buttonGetToTest.Name = "buttonGetToTest"; - buttonGetToTest.Size = new Size(186, 40); + buttonGetToTest.Size = new Size(186, 27); buttonGetToTest.TabIndex = 4; buttonGetToTest.Text = "передать на тесты"; buttonGetToTest.UseVisualStyleBackColor = true; @@ -293,6 +297,28 @@ // openFileDialog.Filter = "txt file|*.txt"; // + // buttonSortByColor + // + buttonSortByColor.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; + buttonSortByColor.Location = new Point(19, 228); + buttonSortByColor.Name = "buttonSortByColor"; + buttonSortByColor.Size = new Size(186, 31); + buttonSortByColor.TabIndex = 7; + buttonSortByColor.Text = "Сортировка по цвету"; + buttonSortByColor.UseVisualStyleBackColor = true; + buttonSortByColor.Click += ButtonSortByColor_Click; + // + // buttonSortByType + // + buttonSortByType.Anchor = AnchorStyles.Right; + buttonSortByType.Location = new Point(19, 184); + buttonSortByType.Name = "buttonSortByType"; + buttonSortByType.Size = new Size(186, 38); + buttonSortByType.TabIndex = 6; + buttonSortByType.Text = "Сортировка по типу"; + buttonSortByType.UseVisualStyleBackColor = true; + buttonSortByType.Click += ButtonSortByType_Click; + // // FormCruisersCollection // AutoScaleDimensions = new SizeF(8F, 20F); @@ -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/ProjectCruiser/FormCruisersCollection.cs b/ProjectCruiser/FormCruisersCollection.cs index 0b1d358..4c5de92 100644 --- a/ProjectCruiser/FormCruisersCollection.cs +++ b/ProjectCruiser/FormCruisersCollection.cs @@ -1,6 +1,7 @@ using Microsoft.Extensions.Logging; using ProjectCruiser.CollectionGenericObjects; using ProjectCruiser.Drawnings; +using System.Windows.Forms; namespace ProjectCruiser { @@ -174,17 +175,11 @@ namespace ProjectCruiser collectionType = CollectionType.List; } - try - { - _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); + CollectionInfo collectionInfo = new CollectionInfo(textBoxCollectionName.Text, collectionType, string.Empty); + + _storageCollection.AddCollection(collectionInfo); _logger.LogInformation("Добавление коллекции"); RerfreshListBoxItems(); - } - catch (Exception ex) - { - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - _logger.LogError($"Ошибка: {ex.Message}", ex.Message); - } } /// @@ -203,7 +198,10 @@ namespace ProjectCruiser { return; } - _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString()); + + CollectionInfo collectionInfo = new CollectionInfo(listBoxCollection.SelectedItem.ToString(), CollectionType.None, string.Empty); + + _storageCollection.DelCollection(collectionInfo); _logger.LogInformation("Коллекция удалена"); RerfreshListBoxItems(); } @@ -216,7 +214,7 @@ namespace ProjectCruiser 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); @@ -237,8 +235,8 @@ namespace ProjectCruiser return; } - ICollectionGenericObjects? collection = - _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty]; + CollectionInfo collectionInfo = new CollectionInfo(listBoxCollection.SelectedItem.ToString(), CollectionType.None, string.Empty); + ICollectionGenericObjects? collection = _storageCollection[collectionInfo]; if (collection == null) { MessageBox.Show("Коллекция не проинициализирована"); @@ -253,6 +251,7 @@ namespace ProjectCruiser break; } panelCompanyTools.Enabled = true; + RerfreshListBoxItems(); } @@ -302,5 +301,39 @@ namespace ProjectCruiser } } } + + /// + /// Сортировка по типу + /// + /// + /// + private void ButtonSortByType_Click(object sender, EventArgs e) + { + CompareCruisers(new DrawningCruiserCompareByType()); + } + + /// + /// Сортировка по цвету + /// + /// + /// + private void ButtonSortByColor_Click(object sender, EventArgs e) + { + CompareCruisers(new DrawningCruiserCompareByColor()); + } + + /// + /// Сортировка по сравнителю + /// + /// Сравнитель объектов + private void CompareCruisers(IComparer comparer) + { + if (_company == null) + { + return; + } + _company.Sort(comparer); + pictureBoxCruiser.Image = _company.Show(); + } } }