diff --git a/ProjectSeaplane/ProjectSeaplane/CollectionGenericObjects/AbstractCompany.cs b/ProjectSeaplane/ProjectSeaplane/CollectionGenericObjects/AbstractCompany.cs index ccc56d8..5eb1604 100644 --- a/ProjectSeaplane/ProjectSeaplane/CollectionGenericObjects/AbstractCompany.cs +++ b/ProjectSeaplane/ProjectSeaplane/CollectionGenericObjects/AbstractCompany.cs @@ -64,7 +64,7 @@ public abstract class AbstractCompany { return -1; } - return company._collection.Insert(plane); + return company._collection.Insert(plane, new DrawiningPlaneEqutables()); } /// @@ -118,6 +118,12 @@ public abstract class AbstractCompany return bitmap; } + /// + /// Сортировка + /// + /// Сравнитель объектов + 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..db95d6d --- /dev/null +++ b/ProjectSeaplane/ProjectSeaplane/CollectionGenericObjects/CollectionInfo.cs @@ -0,0 +1,77 @@ +using ProjectSeaplane.CollectionGenericObjects; + +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 7daf4cc..07a61c1 100644 --- a/ProjectSeaplane/ProjectSeaplane/CollectionGenericObjects/ICollectionGenericObjects.cs +++ b/ProjectSeaplane/ProjectSeaplane/CollectionGenericObjects/ICollectionGenericObjects.cs @@ -1,4 +1,6 @@ -namespace ProjectSeaplane.CollectionGenericObjects; +using ProjectSeaplane.Drawnings; + +namespace ProjectSeaplane.CollectionGenericObjects; /// /// Интерфейс описания действий для набора хранимых объектов @@ -21,16 +23,18 @@ public interface ICollectionGenericObjects /// Добавление объекта в коллекцию /// /// Добавляемый объект + /// Cравнение двух объектов /// true - вставка прошла удачно, false - вставка не удалась - int Insert(T obj); + int Insert(T obj, IEqualityComparer? comparer = null); /// /// Добавление объекта в коллекцию на конкретную позицию /// /// Добавляемый объект /// Позиция + /// Cравнение двух объектов /// true - вставка прошла удачно, false - вставка не удалась - int Insert(T obj, int position); + int Insert(T obj, int position, IEqualityComparer? comparer = null); /// /// Удаление объекта из коллекции с конкретной позиции @@ -56,4 +60,10 @@ public interface ICollectionGenericObjects /// /// Поэлементый вывод элементов коллекции IEnumerable GetItems(); + + /// + /// Сортировка коллекции + /// + /// Сравнитель объектов + void CollectionSort(IComparer comparer); } \ No newline at end of file diff --git a/ProjectSeaplane/ProjectSeaplane/CollectionGenericObjects/ListGenericObjects.cs b/ProjectSeaplane/ProjectSeaplane/CollectionGenericObjects/ListGenericObjects.cs index 54ccb31..a3988ee 100644 --- a/ProjectSeaplane/ProjectSeaplane/CollectionGenericObjects/ListGenericObjects.cs +++ b/ProjectSeaplane/ProjectSeaplane/CollectionGenericObjects/ListGenericObjects.cs @@ -1,4 +1,5 @@ -using ProjectSeaplane.Exceptions; +using ProjectSeaplane.Drawnings; +using ProjectSeaplane.Exceptions; namespace ProjectSeaplane.CollectionGenericObjects; @@ -22,7 +23,7 @@ public class ListGenericObjects : ICollectionGenericObjects public int MaxCount { get { - return _collection.Count; + return _maxCount; } set { @@ -54,24 +55,29 @@ public class ListGenericObjects : ICollectionGenericObjects throw new PositionOutOfCollectionException(position); } } - public int Insert(T obj) + public int Insert(T obj, IEqualityComparer? comparer = null) { - return Insert(obj, _collection.Count); + return Insert(obj, Count, comparer); } - public int Insert(T obj, int position) + public int Insert(T obj, int position, IEqualityComparer? comparer = null) { - if (position > MaxCount) throw new CollectionOverflowException(position); - - if (obj == null) throw new ArgumentNullException(nameof(obj)); + if (_collection.Contains(obj, comparer)) + { + throw new ObjectNotUniqueException(); + } + if (Count >= _maxCount) + { + throw new CollectionOverflowException(Count); + } _collection.Insert(position, obj); - return _collection.Count; + return Count; } public T? Remove(int position) { try { - T obj = _collection[position]; + T? obj = _collection[position]; _collection.RemoveAt(position); return obj; } @@ -83,9 +89,14 @@ public class ListGenericObjects : ICollectionGenericObjects public IEnumerable GetItems() { - for (int i = 0; i < _collection.Count; ++i) + for (int i = 0; i < Count; ++i) { yield return _collection[i]; } } + + public void CollectionSort(IComparer comparer) + { + _collection.Sort(comparer); + } } \ No newline at end of file diff --git a/ProjectSeaplane/ProjectSeaplane/CollectionGenericObjects/MassiveGenericObjects.cs b/ProjectSeaplane/ProjectSeaplane/CollectionGenericObjects/MassiveGenericObjects.cs index d83b80f..6e257d5 100644 --- a/ProjectSeaplane/ProjectSeaplane/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/ProjectSeaplane/ProjectSeaplane/CollectionGenericObjects/MassiveGenericObjects.cs @@ -63,21 +63,25 @@ public class MassiveGenericObjects : ICollectionGenericObjects } } - public int Insert(T obj) + public int Insert(T obj, IEqualityComparer? comparer = null) { - return Insert(obj, 0); + return Insert(obj, 0, comparer); } - public int Insert(T obj, int position) + public int Insert(T obj, int position, IEqualityComparer? comparer = null) { - if (position < 0) + // DO + if (position < 0 || position > _collection.Length - 1) { - return -1; + throw new PositionOutOfCollectionException(); } - if (_collection[position] == null) + if (comparer != null) { - _collection[position] = obj; - return position; + foreach (T? item in _collection) + { + if ((comparer as IEqualityComparer).Equals(obj as DrawningPlane, item as DrawningPlane)) + throw new ObjectNotUniqueException(); + } } for (int i = position; i < Count; i++) @@ -104,7 +108,10 @@ public class MassiveGenericObjects : ICollectionGenericObjects try { T? obj = _collection[position]; - if (obj == null) throw new ObjectNotFoundException(position); + if (obj == null) + { + throw new ObjectNotFoundException(position); + } _collection[position] = null; return obj; } @@ -121,4 +128,10 @@ public class MassiveGenericObjects : ICollectionGenericObjects yield return _collection[i]; } } + + public void CollectionSort(IComparer comparer) + { + Array.Sort(_collection, comparer); + Array.Reverse(_collection); + } } \ No newline at end of file diff --git a/ProjectSeaplane/ProjectSeaplane/CollectionGenericObjects/StorageCollection.cs b/ProjectSeaplane/ProjectSeaplane/CollectionGenericObjects/StorageCollection.cs index 71482df..af209d5 100644 --- a/ProjectSeaplane/ProjectSeaplane/CollectionGenericObjects/StorageCollection.cs +++ b/ProjectSeaplane/ProjectSeaplane/CollectionGenericObjects/StorageCollection.cs @@ -1,6 +1,7 @@ using ProjectSeaplane.Drawnings; using System.Text; using ProjectSeaplane.Exceptions; +using System.IO; namespace ProjectSeaplane.CollectionGenericObjects; @@ -14,12 +15,12 @@ public class StorageCollection /// /// Словарь (хранилище) с коллекциями /// - readonly Dictionary> _storage; + readonly Dictionary> _storage; /// /// Возвращение списка названий коллекций /// - public List Keys => _storage.Keys.ToList(); + public List Keys => _storage.Keys.ToList(); /// /// Ключевое слово, с которого должен начинаться файл @@ -41,7 +42,7 @@ public class StorageCollection /// public StorageCollection() { - _storage = new Dictionary>(); + _storage = new Dictionary>(); } /// @@ -51,21 +52,22 @@ public class StorageCollection /// тип коллекции public void AddCollection(string name, CollectionType collectionType) { - if (string.IsNullOrEmpty(name) || _storage.ContainsKey(name)) + // DO + CollectionInfo collectionInfo = new CollectionInfo(name, collectionType, string.Empty); + if (collectionInfo.Name == null || _storage.ContainsKey(collectionInfo)) { return; } - if (collectionType == CollectionType.None) + switch (collectionType) { - return; - } - if (collectionType == CollectionType.Massive) - { - _storage[name] = new MassiveGenericObjects(); - } - else if (collectionType == CollectionType.List) - { - _storage[name] = new ListGenericObjects(); + case CollectionType.None: + return; + case CollectionType.Massive: + _storage.Add(collectionInfo, new MassiveGenericObjects { }); + return; + case CollectionType.List: + _storage.Add(collectionInfo, new ListGenericObjects { }); + return; } } @@ -75,11 +77,13 @@ public class StorageCollection /// Название коллекции public void DelCollection(string name) { - if (name == null || !_storage.ContainsKey(name)) + // DO + CollectionInfo collectionInfo = new CollectionInfo(name, CollectionType.None, string.Empty); + if (collectionInfo.Name == null || !_storage.ContainsKey(collectionInfo)) { return; } - _storage.Remove(name); + _storage.Remove(collectionInfo); } /// @@ -89,16 +93,15 @@ public class StorageCollection /// public ICollectionGenericObjects? this[string name] { + // DO get { - if (_storage.ContainsKey(name)) - { - return _storage[name]; - } - else + CollectionInfo collectionInfo = new CollectionInfo(name, CollectionType.None, string.Empty); + if (collectionInfo == null || !_storage.ContainsKey(collectionInfo)) { return null; } + return _storage[collectionInfo]; } } @@ -121,16 +124,17 @@ public class StorageCollection using (StreamWriter writer = new StreamWriter(filename)) { writer.WriteLine(_collectionKey); - foreach (KeyValuePair> value in _storage) + foreach (KeyValuePair> value in _storage) { - writer.Write($"{value.Key}{_separatorForKeyValue}{value.Value.GetCollectionType}{_separatorForKeyValue}{value.Value.MaxCount}{_separatorForKeyValue}"); - writer.Write(_separatorItems); + writer.Write($"{value.Key}{_separatorForKeyValue}{value.Value.MaxCount}{_separatorForKeyValue}"); + foreach (T? item in value.Value.GetItems()) { string data = item?.GetDataForSave() ?? string.Empty; if (!string.IsNullOrEmpty(data)) { - writer.Write(data + _separatorItems); + writer.Write(data); + writer.Write(_separatorItems); } } } @@ -164,21 +168,18 @@ public class StorageCollection while (line != null) { string[] record = line.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); - if (record.Length != 4) + if (record.Length != 3) { line = reader.ReadLine(); continue; } - - CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]); - ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType); - if (collection == null) - { + CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(record[0]) ?? + throw new Exception("Не удалось определить информацию коллекции: " + record[0]); + ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionInfo.CollectionType) ?? throw new NullCollectionException("Не удалось создать коллекцию"); - } - collection.MaxCount = Convert.ToInt32(record[2]); + collection.MaxCount = Convert.ToInt32(record[1]); - string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); + string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); foreach (string elem in set) { @@ -195,7 +196,7 @@ public class StorageCollection } } - _storage.Add(record[0], collection); + _storage.Add(collectionInfo, collection); line = reader.ReadLine(); } } diff --git a/ProjectSeaplane/ProjectSeaplane/Drawnings/DrawiningPlaneEqutables.cs b/ProjectSeaplane/ProjectSeaplane/Drawnings/DrawiningPlaneEqutables.cs new file mode 100644 index 0000000..a23dd2b --- /dev/null +++ b/ProjectSeaplane/ProjectSeaplane/Drawnings/DrawiningPlaneEqutables.cs @@ -0,0 +1,69 @@ +using ProjectSeaplane.Entities; +using System.Diagnostics.CodeAnalysis; + +namespace ProjectSeaplane.Drawnings; + +/// +/// Реализация сравнения двух объектов класса-прорисовки +/// +public class DrawiningPlaneEqutables : IEqualityComparer +{ + public bool Equals(DrawningPlane? x, DrawningPlane? y) + { + if (x == null || x.EntityPlane == null) + { + return false; + } + + if (y == null || y.EntityPlane == null) + { + return false; + } + + if (x.GetType().Name != y.GetType().Name) + { + return false; + } + + if (x.EntityPlane.Speed != y.EntityPlane.Speed) + { + return false; + } + + if (x.EntityPlane.Weight != y.EntityPlane.Weight) + { + return false; + } + + if (x.EntityPlane.BodyColor != y.EntityPlane.BodyColor) + { + return false; + } + + if (x is DrawningSeaplane && y is DrawningSeaplane) + { + // DO доделать логику сравнения дополнительных параметров + EntitySeaplane _x = (EntitySeaplane)x.EntityPlane; + EntitySeaplane _y = (EntitySeaplane)x.EntityPlane; + + if (_x.AdditionalColor != _y.AdditionalColor) + { + return false; + } + if (_x.Floats != _y.Floats) + { + return false; + } + if (_x.Boat != _y.Boat) + { + return false; + } + } + + return true; + } + public int GetHashCode([DisallowNull] DrawningPlane obj) + { + return obj.GetHashCode(); + } +} \ No newline at end of file diff --git a/ProjectSeaplane/ProjectSeaplane/Drawnings/DrawningPlaneCompareByColor.cs b/ProjectSeaplane/ProjectSeaplane/Drawnings/DrawningPlaneCompareByColor.cs new file mode 100644 index 0000000..09349a5 --- /dev/null +++ b/ProjectSeaplane/ProjectSeaplane/Drawnings/DrawningPlaneCompareByColor.cs @@ -0,0 +1,39 @@ +namespace ProjectSeaplane.Drawnings; + +/// +/// Сравнение по цвету, скорости, весу +/// +public class DrawningPlaneCompareByColor : IComparer +{ + public int Compare(DrawningPlane? x, DrawningPlane? y) + { + // DO прописать логику сравения по цветам, скорости, весу + if (x == null && y == null) + { + return 0; + } + if (x == null || x.EntityPlane == null) + { + return -1; + } + + if (y == null || y.EntityPlane == null) + { + return 1; + } + + var bodycolorCompare = y.EntityPlane.BodyColor.Name.CompareTo(x.EntityPlane.BodyColor.Name); + if (bodycolorCompare != 0) + { + return bodycolorCompare; + } + + var speedCompare = y.EntityPlane.Speed.CompareTo(x.EntityPlane.Speed); + if (speedCompare != 0) + { + return speedCompare; + } + + return y.EntityPlane.Weight.CompareTo(x.EntityPlane.Weight); + } +} \ No newline at end of file diff --git a/ProjectSeaplane/ProjectSeaplane/Drawnings/DrawningPlaneCompareByType.cs b/ProjectSeaplane/ProjectSeaplane/Drawnings/DrawningPlaneCompareByType.cs new file mode 100644 index 0000000..f78655f --- /dev/null +++ b/ProjectSeaplane/ProjectSeaplane/Drawnings/DrawningPlaneCompareByType.cs @@ -0,0 +1,33 @@ +namespace ProjectSeaplane.Drawnings; + +/// +/// Сравнение по типу, скорости, весу +/// +public class DrawningPlaneCompareByType : IComparer +{ + public int Compare(DrawningPlane? x, DrawningPlane? y) + { + if (x == null && y == null) + { + return 0; + } + if (x == null || x.EntityPlane == null) + { + return -1; + } + if (y == null || y.EntityPlane == null) + { + return 1; + } + if (x.GetType().Name != y.GetType().Name) + { + return x.GetType().Name.CompareTo(y.GetType().Name); + } + var speedCompare = x.EntityPlane.Speed.CompareTo(y.EntityPlane.Speed); + if (speedCompare != 0) + { + return speedCompare; + } + return x.EntityPlane.Weight.CompareTo(y.EntityPlane.Weight); + } +} \ No newline at end of file diff --git a/ProjectSeaplane/ProjectSeaplane/Exceptions/ObjectNotUniqueException.cs b/ProjectSeaplane/ProjectSeaplane/Exceptions/ObjectNotUniqueException.cs new file mode 100644 index 0000000..7b43465 --- /dev/null +++ b/ProjectSeaplane/ProjectSeaplane/Exceptions/ObjectNotUniqueException.cs @@ -0,0 +1,15 @@ +using System.Runtime.Serialization; + +namespace ProjectSeaplane.Exceptions; + +/// +/// Класс, описывающий ошибку наличия такого же объекта в коллекции +/// +[Serializable] +internal class ObjectNotUniqueException : ApplicationException +{ + public ObjectNotUniqueException() : base("Такой объект уже присутствует в колекции") { } + public ObjectNotUniqueException(string message) : base(message) { } + public ObjectNotUniqueException(string message, Exception exception) : base(message, exception) { } + protected ObjectNotUniqueException(SerializationInfo info, StreamingContext contex) : base(info, contex) { } +} \ No newline at end of file diff --git a/ProjectSeaplane/ProjectSeaplane/FormPlaneCollection.Designer.cs b/ProjectSeaplane/ProjectSeaplane/FormPlaneCollection.Designer.cs index 5eee03e..8be59b2 100644 --- a/ProjectSeaplane/ProjectSeaplane/FormPlaneCollection.Designer.cs +++ b/ProjectSeaplane/ProjectSeaplane/FormPlaneCollection.Designer.cs @@ -52,6 +52,8 @@ loadToolStripMenuItem = new ToolStripMenuItem(); saveFileDialog = new SaveFileDialog(); loadFileDialog = new OpenFileDialog(); + buttonSortByType = new Button(); + buttonSortByColor = 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(793, 24); + groupBoxTools.Location = new Point(818, 24); groupBoxTools.Name = "groupBoxTools"; - groupBoxTools.Size = new Size(144, 575); + groupBoxTools.Size = new Size(144, 621); groupBoxTools.TabIndex = 0; groupBoxTools.TabStop = false; groupBoxTools.Text = "Инструменты"; // // panelCompanyTools // + panelCompanyTools.Controls.Add(buttonSortByColor); + panelCompanyTools.Controls.Add(buttonSortByType); panelCompanyTools.Controls.Add(buttonAddPlane); panelCompanyTools.Controls.Add(buttonRefresh); panelCompanyTools.Controls.Add(maskedTextBoxPosition); @@ -84,7 +88,7 @@ panelCompanyTools.Enabled = false; panelCompanyTools.Location = new Point(3, 324); panelCompanyTools.Name = "panelCompanyTools"; - panelCompanyTools.Size = new Size(138, 248); + panelCompanyTools.Size = new Size(138, 294); panelCompanyTools.TabIndex = 10; // // buttonAddPlane @@ -99,7 +103,7 @@ // // buttonRefresh // - buttonRefresh.Location = new Point(3, 202); + buttonRefresh.Location = new Point(3, 152); buttonRefresh.Name = "buttonRefresh"; buttonRefresh.Size = new Size(126, 42); buttonRefresh.TabIndex = 6; @@ -109,7 +113,7 @@ // // maskedTextBoxPosition // - maskedTextBoxPosition.Location = new Point(4, 101); + maskedTextBoxPosition.Location = new Point(3, 51); maskedTextBoxPosition.Mask = "00"; maskedTextBoxPosition.Name = "maskedTextBoxPosition"; maskedTextBoxPosition.Size = new Size(126, 23); @@ -118,7 +122,7 @@ // // buttonGoToCheck // - buttonGoToCheck.Location = new Point(4, 166); + buttonGoToCheck.Location = new Point(3, 116); buttonGoToCheck.Name = "buttonGoToCheck"; buttonGoToCheck.Size = new Size(126, 30); buttonGoToCheck.TabIndex = 5; @@ -128,7 +132,7 @@ // // buttonRemovePlane // - buttonRemovePlane.Location = new Point(4, 130); + buttonRemovePlane.Location = new Point(3, 80); buttonRemovePlane.Name = "buttonRemovePlane"; buttonRemovePlane.Size = new Size(126, 30); buttonRemovePlane.TabIndex = 4; @@ -247,7 +251,7 @@ pictureBox.Dock = DockStyle.Fill; pictureBox.Location = new Point(0, 24); pictureBox.Name = "pictureBox"; - pictureBox.Size = new Size(793, 575); + pictureBox.Size = new Size(818, 621); pictureBox.TabIndex = 1; pictureBox.TabStop = false; // @@ -256,7 +260,7 @@ menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem }); menuStrip.Location = new Point(0, 0); menuStrip.Name = "menuStrip"; - menuStrip.Size = new Size(937, 24); + menuStrip.Size = new Size(962, 24); menuStrip.TabIndex = 2; menuStrip.Text = "menuStrip"; // @@ -267,17 +271,17 @@ файлToolStripMenuItem.Size = new Size(48, 20); файлToolStripMenuItem.Text = "Файл"; // - // SaveToolStripMenuItem + // saveToolStripMenuItem // - saveToolStripMenuItem.Name = "SaveToolStripMenuItem"; + saveToolStripMenuItem.Name = "saveToolStripMenuItem"; saveToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S; saveToolStripMenuItem.Size = new Size(181, 22); saveToolStripMenuItem.Text = "Сохранение"; saveToolStripMenuItem.Click += saveToolStripMenuItem_Click; // - // LoadToolStripMenuItem + // loadToolStripMenuItem // - loadToolStripMenuItem.Name = "LoadToolStripMenuItem"; + loadToolStripMenuItem.Name = "loadToolStripMenuItem"; loadToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L; loadToolStripMenuItem.Size = new Size(181, 22); loadToolStripMenuItem.Text = "Загрузка"; @@ -287,15 +291,35 @@ // saveFileDialog.Filter = "txt file | *.txt"; // - // openFileDialog + // loadFileDialog // loadFileDialog.Filter = "txt file | *.txt"; // + // buttonSortByType + // + buttonSortByType.Location = new Point(4, 200); + buttonSortByType.Name = "buttonSortByType"; + buttonSortByType.Size = new Size(126, 42); + buttonSortByType.TabIndex = 7; + buttonSortByType.Text = "Сортировка по типу"; + buttonSortByType.UseVisualStyleBackColor = true; + buttonSortByType.Click += ButtonSortByType_Click; + // + // buttonSortByColor + // + buttonSortByColor.Location = new Point(3, 248); + buttonSortByColor.Name = "buttonSortByColor"; + buttonSortByColor.Size = new Size(126, 42); + buttonSortByColor.TabIndex = 8; + buttonSortByColor.Text = "Сортировка по цвету"; + buttonSortByColor.UseVisualStyleBackColor = true; + buttonSortByColor.Click += ButtonSortByColor_Click; + // // FormPlaneCollection // AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(937, 599); + ClientSize = new Size(962, 645); Controls.Add(pictureBox); Controls.Add(groupBoxTools); Controls.Add(menuStrip); @@ -340,5 +364,7 @@ private ToolStripMenuItem loadToolStripMenuItem; private SaveFileDialog saveFileDialog; private OpenFileDialog loadFileDialog; + 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 4707c3f..fedc763 100644 --- a/ProjectSeaplane/ProjectSeaplane/FormPlaneCollection.cs +++ b/ProjectSeaplane/ProjectSeaplane/FormPlaneCollection.cs @@ -63,7 +63,7 @@ public partial class FormPlaneCollection : Form /// private void SetPlane(DrawningPlane plane) { - if (_company == null) + if (_company == null || plane == null) { return; } @@ -223,7 +223,7 @@ 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); @@ -302,7 +302,7 @@ public partial class FormPlaneCollection : Form MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); _logger.LogInformation("Загрузка прошла успешно из файла, {filename}", loadFileDialog.FileName); } - catch(Exception ex) + catch (Exception ex) { MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); _logger.LogError("Ошибка {Message}", ex.Message); @@ -310,4 +310,40 @@ public partial class FormPlaneCollection : Form RefreshListBoxItems(); } } + + /// + /// Сортировка по типу + /// + /// + /// + private void ButtonSortByType_Click(object sender, EventArgs e) + { + ComparePlanes(new DrawningPlaneCompareByType()); + } + + /// + /// Сортировка по цвету + /// + /// + /// + private void ButtonSortByColor_Click(object sender, EventArgs e) + { + ComparePlanes(new DrawningPlaneCompareByColor()); + } + + /// + /// Сортировка по сравнителю + /// + /// Сравнитель объектов + private void ComparePlanes(IComparer comparer) + { + if (_company == null) + { + return; + } + + _company.Sort(comparer); + pictureBox.Image = _company.Show(); + } + } \ No newline at end of file diff --git a/ProjectSeaplane/ProjectSeaplane/FormPlaneCollection.resx b/ProjectSeaplane/ProjectSeaplane/FormPlaneCollection.resx index 8b1dfa1..acb2947 100644 --- a/ProjectSeaplane/ProjectSeaplane/FormPlaneCollection.resx +++ b/ProjectSeaplane/ProjectSeaplane/FormPlaneCollection.resx @@ -118,12 +118,12 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - 17, 17 + 146, 17 - 126, 17 + 255, 17 - - 261, 17 + + 17, 17 \ No newline at end of file