From 53756d8da5a6dc499708619443f58ca8ebd7ee12 Mon Sep 17 00:00:00 2001 From: MorozovDanil Date: Tue, 4 Jun 2024 19:37:30 +0400 Subject: [PATCH] =?UTF-8?q?=D0=B3=D0=BE=D1=82=D0=BE=D0=B2=D0=B0=20=D0=BA?= =?UTF-8?q?=20=D1=81=D0=B4=D0=B0=D1=87=D0=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../AbstractCompany.cs | 9 ++- .../CollectionInfo.cs | 49 +++++++++++++ .../ICollectionGenericObjects.cs | 10 ++- .../ListGenericObjects.cs | 23 +++++- .../MassiveGenericObjects.cs | 28 ++++++- .../StorageCollection.cs | 73 ++++++++++--------- .../Drawnings/DrawningShipCompareByColor.cs | 34 +++++++++ .../Drawnings/DrawningShipCompareByType.cs | 35 +++++++++ .../Drawnings/DrawningShipEqutables.cs | 62 ++++++++++++++++ .../Exceptions/ObjectIsEqualException.cs | 21 ++++++ .../FormShipCollection.Designer.cs | 42 +++++++++-- .../FormShipCollection.cs | 27 ++++++- 12 files changed, 361 insertions(+), 52 deletions(-) create mode 100644 ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/CollectionInfo.cs create mode 100644 ProjectContainerShip/ProjectContainerShip/Drawnings/DrawningShipCompareByColor.cs create mode 100644 ProjectContainerShip/ProjectContainerShip/Drawnings/DrawningShipCompareByType.cs create mode 100644 ProjectContainerShip/ProjectContainerShip/Drawnings/DrawningShipEqutables.cs create mode 100644 ProjectContainerShip/ProjectContainerShip/Exceptions/ObjectIsEqualException.cs diff --git a/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/AbstractCompany.cs b/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/AbstractCompany.cs index 721c261..255c629 100644 --- a/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/AbstractCompany.cs +++ b/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/AbstractCompany.cs @@ -55,11 +55,11 @@ public abstract class AbstractCompany /// Перегрузка оператора сложения для класса /// /// Компания - /// Добавляемый объект + /// Добавляемый объект /// public static int operator +(AbstractCompany company, DrawningShip boat) { - return company._collection?.Insert(boat) ?? -1; + return company._collection?.Insert(boat, new DrawningShipEqutables()) ?? -1; } /// @@ -119,4 +119,9 @@ public abstract class AbstractCompany /// protected abstract void SetObjectsPosition(); + /// + /// Сортировка + /// + /// Сравнитель объектов + public void Sort(IComparer comparer) => _collection?.CollectionSort(comparer); } diff --git a/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/CollectionInfo.cs b/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/CollectionInfo.cs new file mode 100644 index 0000000..d7a342a --- /dev/null +++ b/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/CollectionInfo.cs @@ -0,0 +1,49 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectContainerShip.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/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/ICollectionGenericObjects.cs b/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/ICollectionGenericObjects.cs index 0d261d8..645f2c6 100644 --- a/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/ICollectionGenericObjects.cs +++ b/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/ICollectionGenericObjects.cs @@ -19,7 +19,7 @@ public interface ICollectionGenericObjects /// /// Добавляемый объект /// true - вставка прошла удачно, false - вставка не удалась - int Insert (T obj); + int Insert(T obj, IEqualityComparer? comparer = null); /// /// Добавление объекта в коллекцию на конкретную позицию @@ -27,7 +27,7 @@ public interface ICollectionGenericObjects /// /// Добавляемый объект /// /// Позиция /// true - вставка прошла удачно, false - вставка не удалась - int Insert (T obj, int position); + int Insert(T obj, int position, IEqualityComparer? comparer = null); /// /// Удаление объекта из коллекции с конктретной позиции @@ -53,4 +53,10 @@ public interface ICollectionGenericObjects /// /// Поэлементый вывод элементов коллекции IEnumerable GetItems(); + + /// + /// Сортировка коллекции + /// + /// Сравнитель объектов + void CollectionSort(IComparer comparer); } diff --git a/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/ListGenericObjects.cs b/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/ListGenericObjects.cs index e60b1c6..3dc6ace 100644 --- a/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/ListGenericObjects.cs +++ b/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/ListGenericObjects.cs @@ -53,15 +53,29 @@ public class ListGenericObjects : ICollectionGenericObjects 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) { + 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) { + if (comparer != null) + { + if (_collection.Contains(obj, comparer)) + { + throw new ObjectIsEqualException(); + } + } if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position); @@ -87,5 +101,8 @@ public class ListGenericObjects : ICollectionGenericObjects yield return _collection[i]; } } - + void ICollectionGenericObjects.CollectionSort(IComparer comparer) + { + _collection.Sort(comparer); + } } diff --git a/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/MassiveGenericObjects.cs b/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/MassiveGenericObjects.cs index a1f5e9b..bee2a3d 100644 --- a/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/MassiveGenericObjects.cs @@ -1,4 +1,5 @@ -using ProjectContainerShip.Exceptions; +using ProjectContainerShip.Drawnings; +using ProjectContainerShip.Exceptions; namespace ProjectContainerShip.CollectionGenericObjects; @@ -55,8 +56,16 @@ public class MassiveGenericObjects : ICollectionGenericObjects return _collection[position]; } - public int Insert(T obj) + public int Insert(T obj, IEqualityComparer comparer = null) { + if (comparer != null) + { + foreach (T? item in _collection) + { + if ((comparer as IEqualityComparer).Equals(obj as DrawningShip, item as DrawningShip)) + throw new ObjectIsEqualException(); + } + } for (int i = 0; i < Count; i++) { if (_collection[i] == null) @@ -68,8 +77,16 @@ 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) { + if (comparer != null) + { + foreach (T? item in _collection) + { + if ((comparer as IEqualityComparer).Equals(obj as DrawningShip, item as DrawningShip)) + throw new ObjectIsEqualException(); + } + } if (position < 0 || position >= Count) { throw new PositionOutOfCollectionException(position); @@ -119,4 +136,9 @@ public class MassiveGenericObjects : ICollectionGenericObjects yield return _collection[i]; } } + + void ICollectionGenericObjects.CollectionSort(IComparer comparer) + { + Array.Sort(_collection, comparer); + } } \ No newline at end of file diff --git a/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/StorageCollection.cs b/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/StorageCollection.cs index c8b9e7d..3a7d38f 100644 --- a/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/StorageCollection.cs +++ b/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/StorageCollection.cs @@ -18,13 +18,13 @@ public class StorageCollection /// /// Словарь (хранилище) с коллекциями /// - readonly Dictionary> _storages; + readonly Dictionary> _storages; /// /// Возвращение списка названий коллекций /// - public List Keys => _storages.Keys.ToList(); + public List Keys => _storages.Keys.ToList(); /// /// Ключевое слово, с которого должен начинаться файл @@ -47,10 +47,10 @@ public class StorageCollection /// public StorageCollection() { - _storages = new Dictionary>(); + _storages = new Dictionary>(); } - + /// /// Добавление коллекции в хранилище /// @@ -58,17 +58,18 @@ public class StorageCollection /// тип коллекции public void AddCollection(string name, CollectionType collectionType) { - if (string.IsNullOrEmpty(name) || _storages.ContainsKey(name)) + CollectionInfo collectionInfo = new CollectionInfo(name, collectionType, string.Empty); + if (_storages.ContainsKey(collectionInfo)) { return; } switch (collectionType) { case CollectionType.Massive: - _storages[name] = new MassiveGenericObjects(); + _storages[collectionInfo] = new MassiveGenericObjects(); break; case CollectionType.List: - _storages[name] = new ListGenericObjects(); + _storages[collectionInfo] = new ListGenericObjects(); break; default: return; @@ -81,9 +82,10 @@ public class StorageCollection /// Название коллекции public void DelCollection(string name) { - if (_storages.ContainsKey(name)) + CollectionInfo collectionInfo = new CollectionInfo(name, CollectionType.None, string.Empty); + if (_storages.ContainsKey(collectionInfo)) { - _storages.Remove(name); + _storages.Remove(collectionInfo); } } @@ -97,10 +99,9 @@ public class StorageCollection { get { - 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; } } @@ -127,15 +128,13 @@ public class StorageCollection using (StreamWriter sw = new StreamWriter(filename)) { sw.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()) @@ -150,14 +149,15 @@ public class StorageCollection sb.Clear(); } } - } - /// - /// Загрузка информации по кораблям в хранилище из файла - /// - /// Путь и имя файла - public void LoadData(string filename) + + /// + /// Загрузка информации по автомобилям в хранилище из файла + /// + /// Путь и имя файла + /// true - загрузка прошла успешно, false - ошибка при загрузке данных + public void LoadData(string filename) { if (!File.Exists(filename)) { @@ -170,34 +170,37 @@ public class StorageCollection str = sr.ReadLine(); if (str == null || str.Length == 0) throw new Exception("В файле нет данных"); - if (str != _collectionKey.ToString()) + if (!str.StartsWith(_collectionKey)) throw new Exception("В файле неверные данные"); _storages.Clear(); - while ((str = sr.ReadLine()) != null) + string strs = ""; + while ((strs = sr.ReadLine()) != null) { - string[] record = str.Split(_separatorForKeyValue); - if (record.Length != 4) + string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); + 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?.CreateDrawningShip() is T boat) + if (elem?.CreateDrawningShip() is T ship) { try { - if (collection.Insert(boat) == -1) + if (collection.Insert(ship) == -1) + { throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]); + } } catch (CollectionOverflowException ex) { @@ -205,7 +208,7 @@ public class StorageCollection } } } - _storages.Add(record[0], collection); + _storages.Add(collectionInfo, collection); } } } diff --git a/ProjectContainerShip/ProjectContainerShip/Drawnings/DrawningShipCompareByColor.cs b/ProjectContainerShip/ProjectContainerShip/Drawnings/DrawningShipCompareByColor.cs new file mode 100644 index 0000000..2eff457 --- /dev/null +++ b/ProjectContainerShip/ProjectContainerShip/Drawnings/DrawningShipCompareByColor.cs @@ -0,0 +1,34 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectContainerShip.Drawnings; + +public class DrawningShipCompareByColor : IComparer +{ + public int Compare(DrawningShip? x, DrawningShip? y) + { + if (x == null || x.EntityShip == null) + { + return 1; + } + + if (y == null || y.EntityShip == null) + { + return -1; + } + var bodycolorCompare = x.EntityShip.BodyColor.Name.CompareTo(y.EntityShip.BodyColor.Name); + if (bodycolorCompare != 0) + { + return bodycolorCompare; + } + var speedCompare = x.EntityShip.Speed.CompareTo(y.EntityShip.Speed); + if (speedCompare != 0) + { + return speedCompare; + } + return x.EntityShip.Weight.CompareTo(y.EntityShip.Weight); + } +} \ No newline at end of file diff --git a/ProjectContainerShip/ProjectContainerShip/Drawnings/DrawningShipCompareByType.cs b/ProjectContainerShip/ProjectContainerShip/Drawnings/DrawningShipCompareByType.cs new file mode 100644 index 0000000..6f62ca7 --- /dev/null +++ b/ProjectContainerShip/ProjectContainerShip/Drawnings/DrawningShipCompareByType.cs @@ -0,0 +1,35 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectContainerShip.Drawnings; + +public class DrawningShipCompareByType : IComparer +{ + public int Compare(DrawningShip? x, DrawningShip? y) + { + if (x == null || x.EntityShip == null) + { + return 1; + } + + if (y == null || y.EntityShip == null) + { + return -1; + } + + if (x.GetType().Name != y.GetType().Name) + { + return x.GetType().Name.CompareTo(y.GetType().Name); + } + + var speedCompare = x.EntityShip.Speed.CompareTo(y.EntityShip.Speed); + if (speedCompare != 0) + { + return speedCompare; + } + return x.EntityShip.Weight.CompareTo(y.EntityShip.Weight); + } +} \ No newline at end of file diff --git a/ProjectContainerShip/ProjectContainerShip/Drawnings/DrawningShipEqutables.cs b/ProjectContainerShip/ProjectContainerShip/Drawnings/DrawningShipEqutables.cs new file mode 100644 index 0000000..20d1c1e --- /dev/null +++ b/ProjectContainerShip/ProjectContainerShip/Drawnings/DrawningShipEqutables.cs @@ -0,0 +1,62 @@ +using ProjectContainerShip.Entities; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectContainerShip.Drawnings; + +public class DrawningShipEqutables : IEqualityComparer +{ + public bool Equals(DrawningShip? x, DrawningShip? y) + { + if (x == null || x.EntityShip == null) + { + return false; + } + if (y == null || y.EntityShip == null) + { + return false; + } + if (x.GetType().Name != y.GetType().Name) + { + return false; + } + if (x.EntityShip.Speed != y.EntityShip.Speed) + { + return false; + } + if (x.EntityShip.Weight != y.EntityShip.Weight) + { + return false; + } + if (x.EntityShip.BodyColor != y.EntityShip.BodyColor) + { + return false; + } + if (x is DrawningContainerShip && y is DrawningContainerShip) + { + EntityContainerShip _x = (EntityContainerShip)x.EntityShip; + EntityContainerShip _y = (EntityContainerShip)x.EntityShip; + if (_x.AdditionalColor != _y.AdditionalColor) + { + return false; + } + if (_x.Crane != _y.Crane) + { + return false; + } + if (_x.Container != _y.Container) + { + return false; + } + } + return true; + } + public int GetHashCode([DisallowNull] DrawningShip obj) + { + return obj.GetHashCode(); + } +} diff --git a/ProjectContainerShip/ProjectContainerShip/Exceptions/ObjectIsEqualException.cs b/ProjectContainerShip/ProjectContainerShip/Exceptions/ObjectIsEqualException.cs new file mode 100644 index 0000000..5bbb40c --- /dev/null +++ b/ProjectContainerShip/ProjectContainerShip/Exceptions/ObjectIsEqualException.cs @@ -0,0 +1,21 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectContainerShip.Exceptions; + +/// +/// Класс, описывающий ошибку переполнения коллекции +/// +[Serializable] +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) { } +} \ No newline at end of file diff --git a/ProjectContainerShip/ProjectContainerShip/FormShipCollection.Designer.cs b/ProjectContainerShip/ProjectContainerShip/FormShipCollection.Designer.cs index 7271c74..80ee305 100644 --- a/ProjectContainerShip/ProjectContainerShip/FormShipCollection.Designer.cs +++ b/ProjectContainerShip/ProjectContainerShip/FormShipCollection.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,15 +68,17 @@ groupBoxTools.Controls.Add(panelStorage); groupBoxTools.Controls.Add(comboBoxSelectorCompany); groupBoxTools.Dock = DockStyle.Right; - groupBoxTools.Location = new Point(935, 25); + groupBoxTools.Location = new Point(947, 25); groupBoxTools.Name = "groupBoxTools"; - groupBoxTools.Size = new Size(206, 644); + groupBoxTools.Size = new Size(206, 738); groupBoxTools.TabIndex = 0; groupBoxTools.TabStop = false; groupBoxTools.Text = "Инструменты"; // // panelCompanyTools // + panelCompanyTools.Controls.Add(ButtonSortByColor); + panelCompanyTools.Controls.Add(ButtonSortByType); panelCompanyTools.Controls.Add(buttonAddShip); panelCompanyTools.Controls.Add(maskedTextBoxPosition); panelCompanyTools.Controls.Add(buttonRefresh); @@ -83,7 +87,7 @@ panelCompanyTools.Enabled = false; panelCompanyTools.Location = new Point(6, 386); panelCompanyTools.Name = "panelCompanyTools"; - panelCompanyTools.Size = new Size(197, 246); + panelCompanyTools.Size = new Size(197, 346); panelCompanyTools.TabIndex = 9; // // buttonAddShip @@ -251,7 +255,7 @@ pictureBox.Dock = DockStyle.Fill; pictureBox.Location = new Point(0, 25); pictureBox.Name = "pictureBox"; - pictureBox.Size = new Size(935, 644); + pictureBox.Size = new Size(947, 738); pictureBox.TabIndex = 1; pictureBox.TabStop = false; // @@ -260,7 +264,7 @@ menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem }); menuStrip.Location = new Point(0, 0); menuStrip.Name = "menuStrip"; - menuStrip.Size = new Size(1141, 25); + menuStrip.Size = new Size(1153, 25); menuStrip.TabIndex = 2; menuStrip.Text = "menuStrip"; // @@ -296,11 +300,35 @@ openFileDialog.FileName = "openFileDialog1"; openFileDialog.Filter = "txt file | *.txt"; // + // ButtonSortByColor + // + ButtonSortByColor.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + ButtonSortByColor.Location = new Point(6, 289); + ButtonSortByColor.Name = "ButtonSortByColor"; + ButtonSortByColor.RightToLeft = RightToLeft.No; + ButtonSortByColor.Size = new Size(191, 34); + 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(6, 246); + ButtonSortByType.Name = "ButtonSortByType"; + ButtonSortByType.RightToLeft = RightToLeft.No; + ButtonSortByType.Size = new Size(191, 34); + ButtonSortByType.TabIndex = 7; + ButtonSortByType.Text = "Сортировка по типу"; + ButtonSortByType.UseVisualStyleBackColor = true; + ButtonSortByType.Click += ButtonSortByType_Click; + // // FormShipCollection // AutoScaleDimensions = new SizeF(7F, 17F); AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(1141, 669); + ClientSize = new Size(1153, 763); Controls.Add(pictureBox); Controls.Add(groupBoxTools); Controls.Add(menuStrip); @@ -345,5 +373,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/ProjectContainerShip/ProjectContainerShip/FormShipCollection.cs b/ProjectContainerShip/ProjectContainerShip/FormShipCollection.cs index 2e9d1a4..c291de9 100644 --- a/ProjectContainerShip/ProjectContainerShip/FormShipCollection.cs +++ b/ProjectContainerShip/ProjectContainerShip/FormShipCollection.cs @@ -89,6 +89,11 @@ namespace ProjectContainerShip MessageBox.Show("В коллекции превышено допустимое количество элементов"); _logger.LogError("Ошибка: {Message}", ex.Message); } + catch (ObjectIsEqualException ex) + { + MessageBox.Show("Такой объект уже существует в коллекции"); + _logger.LogError("Ошибка: {Message}", ex.Message); + } } /// @@ -220,7 +225,7 @@ namespace ProjectContainerShip 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); @@ -338,5 +343,25 @@ namespace ProjectContainerShip } } } + + private void ButtonSortByType_Click(object sender, EventArgs e) + { + CompareShip(new DrawningShipCompareByType()); + } + + private void ButtonSortByColor_Click(object sender, EventArgs e) + { + CompareShip(new DrawningShipCompareByColor()); + } + + private void CompareShip(IComparer comparer) + { + if (_company == null) + { + return; + } + _company.Sort(comparer); + pictureBox.Image = _company.Show(); + } } } -- 2.25.1