diff --git a/ProjectSeaplane/ProjectSeaplane/CollectionGenericObjects/AbstractCompany.cs b/ProjectSeaplane/ProjectSeaplane/CollectionGenericObjects/AbstractCompany.cs index c424787..2558745 100644 --- a/ProjectSeaplane/ProjectSeaplane/CollectionGenericObjects/AbstractCompany.cs +++ b/ProjectSeaplane/ProjectSeaplane/CollectionGenericObjects/AbstractCompany.cs @@ -10,32 +10,26 @@ public abstract class AbstractCompany /// Размер места (ширина) /// protected readonly int _placeSizeWidth = 180; - /// /// Размер места (высота) /// protected readonly int _placeSizeHeight = 100; - /// /// Ширина окна /// protected readonly int _pictureWidth; - /// /// Высота окна /// protected readonly int _pictureHeight; - /// /// Коллекция cамолетов /// protected ICollectionGenericObjects? _collection = null; - /// /// Вычисление максимального количества элементов, который можно разместить в окне /// private int GetMaxCount => (_pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight))-15; - /// /// Конструктор /// @@ -49,7 +43,6 @@ public abstract class AbstractCompany _collection = collection; _collection.MaxCount = GetMaxCount; } - /// /// Перегрузка оператора сложения для класса /// @@ -58,9 +51,8 @@ public abstract class AbstractCompany /// public static int operator +(AbstractCompany company, DrawingBasicSeaplane seaplane) { - return company._collection.Insert(seaplane); + return company._collection.Insert(seaplane, new DrawingSeaplaneEqutables()); } - /// /// Перегрузка оператора удаления для класса /// @@ -71,7 +63,6 @@ public abstract class AbstractCompany { return company._collection?.Remove(position); } - /// /// Получение случайного объекта из коллекции /// @@ -81,7 +72,6 @@ public abstract class AbstractCompany Random rnd = new(); return _collection?.Get(rnd.Next(GetMaxCount)); } - /// /// Вывод всей коллекции /// @@ -105,15 +95,18 @@ public abstract class AbstractCompany return bitmap; } - /// /// Вывод заднего фона /// /// protected abstract void DrawBackgound(Graphics g); - /// /// Расстановка объектов /// protected abstract void SetObjectsPosition(); + /// + /// Сортировка + /// + /// Сравнитель объектов + public void Sort(IComparer comparer) => _collection?.CollectionSort(comparer); } diff --git a/ProjectSeaplane/ProjectSeaplane/CollectionGenericObjects/CollectionInfo.cs b/ProjectSeaplane/ProjectSeaplane/CollectionGenericObjects/CollectionInfo.cs new file mode 100644 index 0000000..022ed34 --- /dev/null +++ b/ProjectSeaplane/ProjectSeaplane/CollectionGenericObjects/CollectionInfo.cs @@ -0,0 +1,76 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectSeaplane.CollectionGenericObjects; +/// +/// Класс, хранящиий информацию по коллекции +/// +public class CollectionInfo : IEquatable +{ + /// + /// Название + /// + public string Name { get; private set; } + /// + /// Тип + /// + public CollectionType CollectionType { get; private set; } + /// + /// Описание + /// + public string Description { get; private set; } + /// + /// Разделитель для записи информации по объекту в файл + /// + private static readonly string _separator = "-"; + /// + /// Конструктор + /// + /// Название + /// Тип + /// Описание + public CollectionInfo(string name, CollectionType collectionType, string + description) + { + Name = name; + CollectionType = collectionType; + Description = description; + } + /// + /// Создание объекта из строки + /// + /// Строка + /// Объект или null + public static CollectionInfo? GetCollectionInfo(string data) + { + string[] strs = data.Split(_separator, + StringSplitOptions.RemoveEmptyEntries); + if (strs.Length < 1 || strs.Length > 3) + { + return null; + } + return new CollectionInfo(strs[0], + (CollectionType)Enum.Parse(typeof(CollectionType), strs[1]), strs.Length > 2 ? + strs[2] : string.Empty); + } + public override string ToString() + { + return Name + _separator + CollectionType + _separator + Description; + } + public bool Equals(CollectionInfo? other) + { + return Name == other?.Name; + } + public override bool Equals(object? obj) + { + return Equals(obj as CollectionInfo); + } + public override int GetHashCode() + { + return Name.GetHashCode(); + } + +} \ No newline at end of file diff --git a/ProjectSeaplane/ProjectSeaplane/CollectionGenericObjects/ICollectionGenericObjects.cs b/ProjectSeaplane/ProjectSeaplane/CollectionGenericObjects/ICollectionGenericObjects.cs index 5a44d16..50cf067 100644 --- a/ProjectSeaplane/ProjectSeaplane/CollectionGenericObjects/ICollectionGenericObjects.cs +++ b/ProjectSeaplane/ProjectSeaplane/CollectionGenericObjects/ICollectionGenericObjects.cs @@ -11,34 +11,29 @@ public interface ICollectionGenericObjects /// Количество объектов в коллекции /// int Count { get; } - /// /// Установка максимального количества элементов /// int MaxCount { get; set; } - /// /// Добавление объекта в коллекцию /// /// Добавляемый объект /// true - вставка прошла удачно, false - вставка не удалась - int Insert(T obj); - + int Insert(T obj, IEqualityComparer? compaper = null); /// /// Добавление объекта в коллекцию на конкретную позицию /// /// Добавляемый объект /// Позиция /// true - вставка прошла удачно, false - вставка не удалась - int Insert(T obj, int position); - + int Insert(T obj, int position, IEqualityComparer? compaper = null); /// /// Удаление объекта из коллекции с конкретной позиции /// /// Позиция /// true - удаление прошло удачно, false - удаление не удалось T Remove(int position); - /// /// Получение объекта по позиции /// @@ -54,4 +49,9 @@ public interface ICollectionGenericObjects /// /// IEnumerable GetItems(); + /// + /// Сортировка коллекции + /// + /// Сравнитель объектов + void CollectionSort(IComparer comparer); } \ No newline at end of file diff --git a/ProjectSeaplane/ProjectSeaplane/CollectionGenericObjects/ListGenericObjects.cs b/ProjectSeaplane/ProjectSeaplane/CollectionGenericObjects/ListGenericObjects.cs index 6af2a20..0ffdd99 100644 --- a/ProjectSeaplane/ProjectSeaplane/CollectionGenericObjects/ListGenericObjects.cs +++ b/ProjectSeaplane/ProjectSeaplane/CollectionGenericObjects/ListGenericObjects.cs @@ -31,7 +31,6 @@ public class ListGenericObjects : ICollectionGenericObjects } } public CollectionType GetCollectionType => CollectionType.List; - /// /// Конструктор /// @@ -45,19 +44,33 @@ 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? compaper = null) { // TODO проверка, что не превышено максимальное количество элементов // TODO вставка в конец набора + if (compaper != null) + { + if (_collection.Contains(obj, compaper)) + { + 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? compaper = null) { // TODO проверка, что не превышено максимальное количество элементов // TODO проверка позиции // TODO вставка по позиции + if (compaper != null) + { + if (_collection.Contains(obj, compaper)) + { + throw new ObjectIsEqualException(); + } + } if (Count == _maxCount) throw new CollectionOverflowException(Count); if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position); _collection.Insert(position, obj); @@ -72,7 +85,6 @@ public class ListGenericObjects : ICollectionGenericObjects _collection.RemoveAt(position); return obj; } - public IEnumerable GetItems() { for (int i = 0; i < Count; i++) @@ -80,4 +92,8 @@ public class ListGenericObjects : ICollectionGenericObjects yield return _collection[i]; } } + public void CollectionSort(IComparer comparer) + { + _collection.Sort(comparer); + } } diff --git a/ProjectSeaplane/ProjectSeaplane/CollectionGenericObjects/MassiveGenericObjects.cs b/ProjectSeaplane/ProjectSeaplane/CollectionGenericObjects/MassiveGenericObjects.cs index a4d3455..d46a053 100644 --- a/ProjectSeaplane/ProjectSeaplane/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/ProjectSeaplane/ProjectSeaplane/CollectionGenericObjects/MassiveGenericObjects.cs @@ -1,4 +1,5 @@  +using ProjectSeaplane.Drawnings; using ProjectSeaplane.Exceptions; namespace ProjectSeaplane.CollectionGenericObjects; @@ -38,7 +39,6 @@ public class MassiveGenericObjects : ICollectionGenericObjects } } } - public CollectionType GetCollectionType => CollectionType.Massive; /// @@ -56,9 +56,17 @@ public class MassiveGenericObjects : ICollectionGenericObjects return _collection[position]; } - public int Insert(T obj) + public int Insert(T obj, IEqualityComparer? compaper = null) { // TODO вставка в свободное место набора + if (compaper != null) + { + foreach (T? item in _collection) + { + if ((compaper as IEqualityComparer).Equals(obj as DrawingBasicSeaplane, item as DrawingBasicSeaplane)) + throw new ObjectIsEqualException(); + } + } int index = 0; while (index < _collection.Length) { @@ -73,25 +81,31 @@ public class MassiveGenericObjects : ICollectionGenericObjects throw new CollectionOverflowException(Count); } - public int Insert(T obj, int position) + public int Insert(T obj, int position, IEqualityComparer? compaper = null) { // TODO проверка позиции // TODO проверка, что элемент массива по этой позиции пустой, если нет, то // ищется свободное место после этой позиции и идет вставка туда // если нет после, ищем до // TODO вставка + if (compaper != null) + { + foreach (T? item in _collection) + { + if ((compaper as IEqualityComparer).Equals(obj as DrawingBasicSeaplane, item as DrawingBasicSeaplane)) + throw new ObjectIsEqualException(); + } + } if (position >= _collection.Length || position < 0) { throw new PositionOutOfCollectionException(position); - } - + } if (_collection[position] == null) { _collection[position] = obj; return position; } int index; - for (index = position + 1; index < _collection.Length; ++index) { if (_collection[index] == null) @@ -100,7 +114,6 @@ public class MassiveGenericObjects : ICollectionGenericObjects return position; } } - for (index = position - 1; index >= 0; --index) { if (_collection[index] == null) @@ -111,7 +124,6 @@ public class MassiveGenericObjects : ICollectionGenericObjects } throw new CollectionOverflowException(Count); } - public T Remove(int position) { // TODO проверка позиции @@ -122,7 +134,6 @@ public class MassiveGenericObjects : ICollectionGenericObjects _collection[position] = null; return obj; } - public IEnumerable GetItems() { for (int i = 0; i < _collection.Length; i++) @@ -130,4 +141,8 @@ public class MassiveGenericObjects : ICollectionGenericObjects yield return _collection[i]; } } + public void CollectionSort(IComparer comparer) + { + Array.Sort(_collection, comparer); + } } \ No newline at end of file diff --git a/ProjectSeaplane/ProjectSeaplane/CollectionGenericObjects/StorageCollection.cs b/ProjectSeaplane/ProjectSeaplane/CollectionGenericObjects/StorageCollection.cs index d8c7c1c..56b9166 100644 --- a/ProjectSeaplane/ProjectSeaplane/CollectionGenericObjects/StorageCollection.cs +++ b/ProjectSeaplane/ProjectSeaplane/CollectionGenericObjects/StorageCollection.cs @@ -13,34 +13,29 @@ public class StorageCollection /// /// Словарь (хранилище) с коллекциями /// - readonly Dictionary> _storages; - + readonly Dictionary> _storages; /// /// Возвращение списка названий коллекций /// - public List Keys => _storages.Keys.ToList(); - + public List Keys => _storages.Keys.ToList(); /// /// Ключевое слово, с которого должен начинаться файл /// private readonly string _collectionKey = "CollectionsStorage"; - /// /// Разделитель для записи ключа и значения элемента словаря /// private readonly string _separatorForKeyValue = "|"; - /// /// Разделитель для записей коллекции данных в файл /// - private readonly string _separatorItems = ";"; - + private readonly string _separatorItems = ";"; /// /// Конструктор /// public StorageCollection() { - _storages = new Dictionary>(); + _storages = new Dictionary>(); } /// /// Добавление коллекции в хранилище @@ -52,12 +47,13 @@ public class StorageCollection // TODO проверка, что name не пустой и нет в словаре записи с таким ключом // TODO Прописать логику для добавления - if (_storages.ContainsKey(name)) return; + CollectionInfo collectionInfo = new CollectionInfo(name, collectionType, string.Empty); + if (_storages.ContainsKey(collectionInfo)) return; if (collectionType == CollectionType.None) return; else if (collectionType == CollectionType.Massive) - _storages[name] = new MassiveGenericObjects(); + _storages[collectionInfo] = new MassiveGenericObjects(); else if (collectionType == CollectionType.List) - _storages[name] = new ListGenericObjects(); + _storages[collectionInfo] = new ListGenericObjects(); } /// /// Удаление коллекции @@ -66,10 +62,10 @@ public class StorageCollection 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); } - /// /// Доступ к коллекции /// @@ -80,13 +76,14 @@ public class StorageCollection 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; } - } - + } /// /// Сохранение информации по самолетам в хранилище в файл /// @@ -106,7 +103,7 @@ public class StorageCollection using (StreamWriter writer = new StreamWriter(filename)) { writer.Write(_collectionKey); - foreach (KeyValuePair> value in _storages) + foreach (KeyValuePair> value in _storages) { StringBuilder sb = new(); sb.Append(Environment.NewLine); @@ -117,8 +114,6 @@ public class StorageCollection } sb.Append(value.Key); sb.Append(_separatorForKeyValue); - sb.Append(value.Value.GetCollectionType); - sb.Append(_separatorForKeyValue); sb.Append(value.Value.MaxCount); sb.Append(_separatorForKeyValue); foreach (T? item in value.Value.GetItems()) @@ -165,18 +160,18 @@ public class StorageCollection { 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); 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?.CreateDrawningBasicSeaplane() is T seaplane) @@ -193,7 +188,7 @@ public class StorageCollection } } } - _storages.Add(record[0], collection); + _storages.Add(collectionInfo, collection); } } diff --git a/ProjectSeaplane/ProjectSeaplane/Drawnings/DrawingSeaplaneEqutables.cs b/ProjectSeaplane/ProjectSeaplane/Drawnings/DrawingSeaplaneEqutables.cs new file mode 100644 index 0000000..9809a58 --- /dev/null +++ b/ProjectSeaplane/ProjectSeaplane/Drawnings/DrawingSeaplaneEqutables.cs @@ -0,0 +1,65 @@ +using ProjectSeaplane.Entities; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectSeaplane.Drawnings; +/// +/// Реализация сравнения двух объектов класса-прорисовки +/// +public class DrawingSeaplaneEqutables : IEqualityComparer +{ + public bool Equals(DrawingBasicSeaplane? x, DrawingBasicSeaplane? y) + { + if (x == null || x.EntityBasicSeaplane == null) + { + return false; + } + if (y == null || y.EntityBasicSeaplane == null) + { + return false; + } + if (x.GetType().Name != y.GetType().Name) + { + return false; + } + if (x.EntityBasicSeaplane.Speed != y.EntityBasicSeaplane.Speed) + { + return false; + } + if (x.EntityBasicSeaplane.Weight != y.EntityBasicSeaplane.Weight) + { + return false; + } + if (x.EntityBasicSeaplane.BodyColor != y.EntityBasicSeaplane.BodyColor) + { + return false; + } + if (x is EntitySeaplane && y is EntitySeaplane) + { + // TODO доделать логику сравнения дополнительных параметров + EntitySeaplane _x = (EntitySeaplane)x.EntityBasicSeaplane; + EntitySeaplane _y = (EntitySeaplane)x.EntityBasicSeaplane; + if (_x.AdditionalColor != _y.AdditionalColor) + { + return false; + } + if (_x.Radar != _y.Radar) + { + return false; + } + if (_x.LandingGear != _y.LandingGear) + { + return false; + } + } + return true; + } + public int GetHashCode([DisallowNull] DrawingBasicSeaplane? obj) + { + return obj.GetHashCode(); + } +} \ No newline at end of file diff --git a/ProjectSeaplane/ProjectSeaplane/Drawnings/SeaplaneCompareByColor.cs b/ProjectSeaplane/ProjectSeaplane/Drawnings/SeaplaneCompareByColor.cs new file mode 100644 index 0000000..b8f4692 --- /dev/null +++ b/ProjectSeaplane/ProjectSeaplane/Drawnings/SeaplaneCompareByColor.cs @@ -0,0 +1,36 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectSeaplane.Drawnings; +/// +/// сравнение по цвету, скорости и весу +/// +public class SeaplaneCompareByColor : IComparer +{ + public int Compare(DrawingBasicSeaplane? x, DrawingBasicSeaplane? y) + { + if (x == null || x.EntityBasicSeaplane == null) + { + return 1; + } + + if (y == null || y.EntityBasicSeaplane == null) + { + return -1; + } + var bodycolorCompare = x.EntityBasicSeaplane.BodyColor.Name.CompareTo(y.EntityBasicSeaplane.BodyColor.Name); + if (bodycolorCompare != 0) + { + return bodycolorCompare; + } + var speedCompare = x.EntityBasicSeaplane.Speed.CompareTo(y.EntityBasicSeaplane.Speed); + if (speedCompare != 0) + { + return speedCompare; + } + return x.EntityBasicSeaplane.Weight.CompareTo(y.EntityBasicSeaplane.Weight); + } +} diff --git a/ProjectSeaplane/ProjectSeaplane/Drawnings/SeaplaneCompareByType.cs b/ProjectSeaplane/ProjectSeaplane/Drawnings/SeaplaneCompareByType.cs new file mode 100644 index 0000000..4612271 --- /dev/null +++ b/ProjectSeaplane/ProjectSeaplane/Drawnings/SeaplaneCompareByType.cs @@ -0,0 +1,34 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectSeaplane.Drawnings; +/// +/// Сравнение по типу, скорости, весу +/// +public class SeaplaneCompareByType : IComparer +{ + public int Compare(DrawingBasicSeaplane? x, DrawingBasicSeaplane? y) + { + if (x == null || x.EntityBasicSeaplane == null) + { + return 1; + } + if (y == null || y.EntityBasicSeaplane == null) + { + return -1; + } + if (x.GetType().Name != y.GetType().Name) + { + return x.GetType().Name.CompareTo(y.GetType().Name); + } + var speedCompare = x.EntityBasicSeaplane.Speed.CompareTo(y.EntityBasicSeaplane.Speed); + if (speedCompare != 0) + { + return speedCompare; + } + return x.EntityBasicSeaplane.Weight.CompareTo(y.EntityBasicSeaplane.Weight); + } +} diff --git a/ProjectSeaplane/ProjectSeaplane/Exceptions/ObjectIsEqualException.cs b/ProjectSeaplane/ProjectSeaplane/Exceptions/ObjectIsEqualException.cs new file mode 100644 index 0000000..04635c3 --- /dev/null +++ b/ProjectSeaplane/ProjectSeaplane/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 ProjectSeaplane.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/ProjectSeaplane/ProjectSeaplane/FormPlaneCollection.Designer.cs b/ProjectSeaplane/ProjectSeaplane/FormPlaneCollection.Designer.cs index 4d275b8..a467101 100644 --- a/ProjectSeaplane/ProjectSeaplane/FormPlaneCollection.Designer.cs +++ b/ProjectSeaplane/ProjectSeaplane/FormPlaneCollection.Designer.cs @@ -52,6 +52,8 @@ loadToolStripMenuItem = new ToolStripMenuItem(); openFileDialog = new OpenFileDialog(); saveFileDialog = new SaveFileDialog(); + buttonSortByColor = new Button(); + buttonSortByType = new Button(); groupBoxTools.SuspendLayout(); panelCompanyTools.SuspendLayout(); panelStorage.SuspendLayout(); @@ -75,15 +77,17 @@ // // panelCompanyTools // + panelCompanyTools.Controls.Add(buttonSortByColor); + panelCompanyTools.Controls.Add(buttonSortByType); panelCompanyTools.Controls.Add(buttonAddBasicSeaplane); panelCompanyTools.Controls.Add(buttonRefresh); panelCompanyTools.Controls.Add(maskedTextBox); panelCompanyTools.Controls.Add(buttonGoToCheck); panelCompanyTools.Controls.Add(buttonDelSeaplane); panelCompanyTools.Dock = DockStyle.Bottom; - panelCompanyTools.Location = new Point(3, 361); + panelCompanyTools.Location = new Point(3, 301); panelCompanyTools.Name = "panelCompanyTools"; - panelCompanyTools.Size = new Size(174, 226); + panelCompanyTools.Size = new Size(174, 286); panelCompanyTools.TabIndex = 9; // // buttonAddBasicSeaplane @@ -102,7 +106,7 @@ // buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; buttonRefresh.FlatStyle = FlatStyle.Flat; - buttonRefresh.Location = new Point(0, 183); + buttonRefresh.Location = new Point(0, 148); buttonRefresh.Name = "buttonRefresh"; buttonRefresh.Size = new Size(174, 31); buttonRefresh.TabIndex = 6; @@ -112,7 +116,7 @@ // // maskedTextBox // - maskedTextBox.Location = new Point(0, 83); + maskedTextBox.Location = new Point(0, 48); maskedTextBox.Mask = "00"; maskedTextBox.Name = "maskedTextBox"; maskedTextBox.Size = new Size(174, 23); @@ -123,7 +127,7 @@ // buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; buttonGoToCheck.FlatStyle = FlatStyle.Flat; - buttonGoToCheck.Location = new Point(0, 148); + buttonGoToCheck.Location = new Point(0, 113); buttonGoToCheck.Name = "buttonGoToCheck"; buttonGoToCheck.Size = new Size(174, 29); buttonGoToCheck.TabIndex = 5; @@ -135,7 +139,7 @@ // buttonDelSeaplane.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; buttonDelSeaplane.FlatStyle = FlatStyle.Flat; - buttonDelSeaplane.Location = new Point(0, 112); + buttonDelSeaplane.Location = new Point(0, 77); buttonDelSeaplane.Name = "buttonDelSeaplane"; buttonDelSeaplane.Size = new Size(174, 30); buttonDelSeaplane.TabIndex = 4; @@ -145,9 +149,9 @@ // // buttonCreateCompany // - buttonCreateCompany.Location = new Point(3, 334); + buttonCreateCompany.Location = new Point(3, 269); buttonCreateCompany.Name = "buttonCreateCompany"; - buttonCreateCompany.Size = new Size(171, 26); + buttonCreateCompany.Size = new Size(174, 26); buttonCreateCompany.TabIndex = 8; buttonCreateCompany.Text = "Создать компанию"; buttonCreateCompany.UseVisualStyleBackColor = true; @@ -165,12 +169,12 @@ panelStorage.Dock = DockStyle.Top; panelStorage.Location = new Point(3, 19); panelStorage.Name = "panelStorage"; - panelStorage.Size = new Size(174, 280); + panelStorage.Size = new Size(174, 219); panelStorage.TabIndex = 7; // // buttonCollectionDel // - buttonCollectionDel.Location = new Point(0, 234); + buttonCollectionDel.Location = new Point(0, 189); buttonCollectionDel.Name = "buttonCollectionDel"; buttonCollectionDel.Size = new Size(171, 26); buttonCollectionDel.TabIndex = 6; @@ -184,7 +188,7 @@ listBoxCollection.ItemHeight = 15; listBoxCollection.Location = new Point(3, 104); listBoxCollection.Name = "listBoxCollection"; - listBoxCollection.Size = new Size(168, 124); + listBoxCollection.Size = new Size(168, 79); listBoxCollection.TabIndex = 5; // // buttonCollectionAdd @@ -240,9 +244,9 @@ СomboBoxSelectorCompany.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; СomboBoxSelectorCompany.FormattingEnabled = true; СomboBoxSelectorCompany.Items.AddRange(new object[] { "Хранилище" }); - СomboBoxSelectorCompany.Location = new Point(3, 305); + СomboBoxSelectorCompany.Location = new Point(3, 240); СomboBoxSelectorCompany.Name = "СomboBoxSelectorCompany"; - СomboBoxSelectorCompany.Size = new Size(171, 23); + СomboBoxSelectorCompany.Size = new Size(174, 23); СomboBoxSelectorCompany.TabIndex = 0; СomboBoxSelectorCompany.SelectedIndexChanged += СomboBoxSelectorCompany_SelectedIndexChanged; // @@ -295,6 +299,30 @@ // saveFileDialog.Filter = "txt file |*.txt"; // + // buttonSortByColor + // + buttonSortByColor.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + buttonSortByColor.FlatStyle = FlatStyle.Flat; + buttonSortByColor.Location = new Point(0, 230); + buttonSortByColor.Name = "buttonSortByColor"; + buttonSortByColor.Size = new Size(171, 37); + buttonSortByColor.TabIndex = 8; + buttonSortByColor.Text = "Сортировка по цвету"; + buttonSortByColor.UseVisualStyleBackColor = true; + buttonSortByColor.Click += buttonSortByColor_Click; + // + // buttonSortByType + // + buttonSortByType.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + buttonSortByType.FlatStyle = FlatStyle.Flat; + buttonSortByType.Location = new Point(0, 185); + buttonSortByType.Name = "buttonSortByType"; + buttonSortByType.Size = new Size(171, 39); + buttonSortByType.TabIndex = 7; + buttonSortByType.Text = "Сортировка по типу"; + buttonSortByType.UseVisualStyleBackColor = true; + buttonSortByType.Click += buttonSortByType_Click; + // // FormPlaneCollection // AutoScaleDimensions = new SizeF(7F, 15F); @@ -344,5 +372,7 @@ private ToolStripMenuItem loadToolStripMenuItem; private OpenFileDialog openFileDialog; private SaveFileDialog saveFileDialog; + private Button buttonSortByColor; + private Button buttonSortByType; } } \ No newline at end of file diff --git a/ProjectSeaplane/ProjectSeaplane/FormPlaneCollection.cs b/ProjectSeaplane/ProjectSeaplane/FormPlaneCollection.cs index 41035ed..e069647 100644 --- a/ProjectSeaplane/ProjectSeaplane/FormPlaneCollection.cs +++ b/ProjectSeaplane/ProjectSeaplane/FormPlaneCollection.cs @@ -87,9 +87,12 @@ public partial class FormPlaneCollection : Form MessageBox.Show("Выход за границы коллекции"); _logger.LogError("Ошибка: {Message}", ex.Message); } + catch (ObjectIsEqualException ex) + { + MessageBox.Show("Не удалось добавить объект, такой объект уже является частью коллекции"); + _logger.LogError("Ошибка: {Message}", ex.Message); + } } - - /// /// Удаление объекта /// @@ -101,12 +104,10 @@ public partial class FormPlaneCollection : Form { return; } - if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) { return; } - int pos = Convert.ToInt32(maskedTextBox.Text); try { @@ -123,7 +124,6 @@ public partial class FormPlaneCollection : Form _logger.LogError("Ошибка: {Message}", ex.Message); } } - /// /// Передача объекта в другую форму /// @@ -167,7 +167,6 @@ public partial class FormPlaneCollection : Form MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); } } - /// /// Перерисовка коллекции /// @@ -182,9 +181,6 @@ public partial class FormPlaneCollection : Form pictureBox.Image = _company.Show(); } - - - /// /// добавление коллекции /// @@ -228,14 +224,13 @@ public partial class FormPlaneCollection : 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); } } } - /// /// удаление коллекции /// @@ -292,7 +287,6 @@ public partial class FormPlaneCollection : Form RerfreshListBoxItems(); } - /// /// Обработка нажатия "Сохранение" /// @@ -317,7 +311,6 @@ public partial class FormPlaneCollection : Form } } } - /// /// Обработка нажатия "Загрузка" /// @@ -342,5 +335,36 @@ public partial class FormPlaneCollection : Form } } + /// + /// Сортировка по типу + /// + /// + /// + private void buttonSortByType_Click(object sender, EventArgs e) + { + CompareSeaplane(new SeaplaneCompareByType()); + } + /// + /// Cортировка по цвету + /// + /// + /// + private void buttonSortByColor_Click(object sender, EventArgs e) + { + CompareSeaplane(new SeaplaneCompareByColor()); + } + /// + /// Сортировка по сравнителю + /// + /// Сравнитель объектов + private void CompareSeaplane(IComparer comparer) + { + if (_company == null) + { + return; + } + _company.Sort(comparer); + pictureBox.Image = _company.Show(); + } } diff --git a/ProjectSeaplane/ProjectSeaplane/FormPlaneCollection.resx b/ProjectSeaplane/ProjectSeaplane/FormPlaneCollection.resx index 8a67c96..7bd4457 100644 --- a/ProjectSeaplane/ProjectSeaplane/FormPlaneCollection.resx +++ b/ProjectSeaplane/ProjectSeaplane/FormPlaneCollection.resx @@ -126,4 +126,7 @@ 271, 17 + + 50 + \ No newline at end of file