diff --git a/WinFormsAppExcavator/WinFormsAppExcavator/CollectionGenericObjects/AbstractCompany.cs b/WinFormsAppExcavator/WinFormsAppExcavator/CollectionGenericObjects/AbstractCompany.cs index 64bbfc8..6243cb3 100644 --- a/WinFormsAppExcavator/WinFormsAppExcavator/CollectionGenericObjects/AbstractCompany.cs +++ b/WinFormsAppExcavator/WinFormsAppExcavator/CollectionGenericObjects/AbstractCompany.cs @@ -56,7 +56,7 @@ public abstract class AbstractCompany /// public static int operator +(AbstractCompany company, DrawingExcavatorEmpty excavator) { - return company._collection.Insert(excavator); + return company._collection.Insert(excavator, new DrawningExcavatorEqutables()); } /// @@ -115,4 +115,10 @@ public abstract class AbstractCompany /// Расстановка объектов /// protected abstract void SetObjectsPosition(); + + /// + /// Сортировка + /// + /// Сравнитель объектов + public void Sort(IComparer comparer) => _collection?.CollectionSort(comparer); } diff --git a/WinFormsAppExcavator/WinFormsAppExcavator/CollectionGenericObjects/CollectionInfo.cs b/WinFormsAppExcavator/WinFormsAppExcavator/CollectionGenericObjects/CollectionInfo.cs new file mode 100644 index 0000000..88da357 --- /dev/null +++ b/WinFormsAppExcavator/WinFormsAppExcavator/CollectionGenericObjects/CollectionInfo.cs @@ -0,0 +1,76 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace WinFormsAppExcavator.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/WinFormsAppExcavator/WinFormsAppExcavator/CollectionGenericObjects/ICollectionGenericObjects.cs b/WinFormsAppExcavator/WinFormsAppExcavator/CollectionGenericObjects/ICollectionGenericObjects.cs index 5daa78c..a3cc630 100644 --- a/WinFormsAppExcavator/WinFormsAppExcavator/CollectionGenericObjects/ICollectionGenericObjects.cs +++ b/WinFormsAppExcavator/WinFormsAppExcavator/CollectionGenericObjects/ICollectionGenericObjects.cs @@ -1,4 +1,6 @@ -namespace WinFormsAppExcavator.CollectionGenericObjects; +using WinFormsAppExcavator.Drawings; + +namespace WinFormsAppExcavator.CollectionGenericObjects; /// /// Интерфейс описания действий для набора хранимых объектов @@ -22,7 +24,7 @@ public interface ICollectionGenericObjects /// /// Добавляемый объект /// true - вставка прошла удачно, false - вставка не удалась - int Insert(T obj); + int Insert(T obj, IEqualityComparer? compaper = null); /// /// Добавление объекта в коллекцию на конкретную позицию @@ -30,7 +32,7 @@ public interface ICollectionGenericObjects /// Добавляемый объект /// Позиция /// true - вставка прошла удачно, false - вставка не удалась - int Insert(T obj, int position); + int Insert(T obj, int position, IEqualityComparer? compaper = null); /// /// Удаление объекта из коллекции с конкретной позиции @@ -54,5 +56,11 @@ public interface ICollectionGenericObjects /// /// IEnumerable GetItems(); + /// + /// Сортировка коллекции + /// + /// Сравнитель объектов + void CollectionSort(IComparer comparer); + } diff --git a/WinFormsAppExcavator/WinFormsAppExcavator/CollectionGenericObjects/ListGenericObjects.cs b/WinFormsAppExcavator/WinFormsAppExcavator/CollectionGenericObjects/ListGenericObjects.cs index 377caf4..7a66f9f 100644 --- a/WinFormsAppExcavator/WinFormsAppExcavator/CollectionGenericObjects/ListGenericObjects.cs +++ b/WinFormsAppExcavator/WinFormsAppExcavator/CollectionGenericObjects/ListGenericObjects.cs @@ -1,4 +1,6 @@  +using ProjectWarmlyShip.Exceptions; +using WinFormsAppExcavator.Drawings; using WinFormsAppExcavator.Exceptions; namespace WinFormsAppExcavator.CollectionGenericObjects; @@ -44,14 +46,28 @@ 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) { + if (compaper != null) + { + if (_collection.Contains(obj, compaper)) + { + throw new ObjectIsEqualException(); + } + } if (Count == _maxCount) throw new CollectionOverflowException(); _collection.Add(obj); return Count; } - public int Insert(T obj, int position) + public int Insert(T obj, int position, IEqualityComparer? compaper = null) { + 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,4 +88,9 @@ public class ListGenericObjects : ICollectionGenericObjects yield return _collection[i]; } } + + public void CollectionSort(IComparer comparer) + { + _collection.Sort(comparer); + } } diff --git a/WinFormsAppExcavator/WinFormsAppExcavator/CollectionGenericObjects/MassiveGenericObjects.cs b/WinFormsAppExcavator/WinFormsAppExcavator/CollectionGenericObjects/MassiveGenericObjects.cs index f1afb56..f845c17 100644 --- a/WinFormsAppExcavator/WinFormsAppExcavator/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/WinFormsAppExcavator/WinFormsAppExcavator/CollectionGenericObjects/MassiveGenericObjects.cs @@ -1,4 +1,6 @@  +using ProjectWarmlyShip.Exceptions; +using WinFormsAppExcavator.Drawings; using WinFormsAppExcavator.Exceptions; namespace WinFormsAppExcavator.CollectionGenericObjects; @@ -55,8 +57,16 @@ public class MassiveGenericObjects : ICollectionGenericObjects return _collection[position]; } - public int Insert(T obj) + public int Insert(T obj, IEqualityComparer? compaper = null) { + if (compaper != null) + { + foreach (T? item in _collection) + { + if ((compaper as IEqualityComparer).Equals(obj as DrawingExcavatorEmpty, item as DrawingExcavatorEmpty)) + throw new ObjectIsEqualException(); + } + } int index = 0; while (index < _collection.Length) { @@ -72,8 +82,16 @@ public class MassiveGenericObjects : ICollectionGenericObjects } - public int Insert(T obj, int position) + public int Insert(T obj, int position, IEqualityComparer? compaper = null) { + if (compaper != null) + { + foreach (T? item in _collection) + { + if ((compaper as IEqualityComparer).Equals(obj as DrawingExcavatorEmpty, item as DrawingExcavatorEmpty)) + throw new ObjectIsEqualException(); + } + } if (position >= _collection.Length || position < 0) { throw new PositionOutOfCollectionException(position); @@ -125,4 +143,9 @@ public class MassiveGenericObjects : ICollectionGenericObjects yield return _collection[i]; } } + + public void CollectionSort(IComparer comparer) + { + Array.Sort(_collection, comparer); + } } diff --git a/WinFormsAppExcavator/WinFormsAppExcavator/CollectionGenericObjects/StorageCollection.cs b/WinFormsAppExcavator/WinFormsAppExcavator/CollectionGenericObjects/StorageCollection.cs index 806a234..c3d1dbe 100644 --- a/WinFormsAppExcavator/WinFormsAppExcavator/CollectionGenericObjects/StorageCollection.cs +++ b/WinFormsAppExcavator/WinFormsAppExcavator/CollectionGenericObjects/StorageCollection.cs @@ -13,17 +13,17 @@ public class StorageCollection /// /// Словарь (хранилище) с коллекциями /// - readonly Dictionary> _storages; + readonly Dictionary> _storages; /// /// Возвращение списка названий коллекций /// - public List Keys => _storages.Keys.ToList(); + public List Keys => _storages.Keys.ToList(); /// /// Конструктор /// public StorageCollection() { - _storages = new Dictionary>(); + _storages = new Dictionary>(); } /// /// Добавление коллекции в хранилище @@ -34,13 +34,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(); } /// /// Удаление коллекции @@ -48,9 +48,9 @@ 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); } /// @@ -62,9 +62,10 @@ 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; @@ -105,7 +106,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); @@ -115,8 +116,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()) @@ -161,18 +160,19 @@ public class StorageCollection while ((strs = fs.ReadLine()) != null) { string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); - if (record.Length != 4) + if (record.Length != 3) { continue; } - CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]); - ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType); + CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(record[0]) ?? throw new Exception("Не удалось определить информацию коллекции: " + record[0]); + + ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionInfo.CollectionType); 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?.CreateDrawningExcavatorEmpty() is T excavator) @@ -190,7 +190,7 @@ public class StorageCollection } } } - _storages.Add(record[0], collection); + _storages.Add(collectionInfo, collection); } } } diff --git a/WinFormsAppExcavator/WinFormsAppExcavator/Drawings/DrawningExcavatorEqutables.cs b/WinFormsAppExcavator/WinFormsAppExcavator/Drawings/DrawningExcavatorEqutables.cs new file mode 100644 index 0000000..7baf755 --- /dev/null +++ b/WinFormsAppExcavator/WinFormsAppExcavator/Drawings/DrawningExcavatorEqutables.cs @@ -0,0 +1,68 @@ + + +using System.Diagnostics.CodeAnalysis; +using WinFormsAppExcavator.Entity; + +namespace WinFormsAppExcavator.Drawings; +/// +/// Реализация сравнения двух объектов класса-прорисовки +/// +public class DrawningExcavatorEqutables : IEqualityComparer +{ + public bool Equals(DrawingExcavatorEmpty? x, DrawingExcavatorEmpty? y) + { + if (x == null || x.EntityExcavatorEmpty == null) + { + return false; + } + if (y == null || y.EntityExcavatorEmpty == null) + { + return false; + } + if (x.GetType().Name != y.GetType().Name) + { + return false; + } + if (x.EntityExcavatorEmpty.Speed != y.EntityExcavatorEmpty.Speed) + { + return false; + } + if (x.EntityExcavatorEmpty.Weight != y.EntityExcavatorEmpty.Weight) + { + return false; + } + if (x.EntityExcavatorEmpty.BodyColor != y.EntityExcavatorEmpty.BodyColor) + { + return false; + } + if (x is EntityExcavator && y is EntityExcavator) + { + // TODO доделать логику сравнения дополнительных параметров + EntityExcavator _x = (EntityExcavator)x.EntityExcavatorEmpty; + EntityExcavator _y = (EntityExcavator)x.EntityExcavatorEmpty; + if (_x.AdditionalColor != _y.AdditionalColor) + { + return false; + } + if (_x.Bucket != _y.Bucket) + { + return false; + } + if (_x.BulldozerDump != _y.BulldozerDump) + { + return false; + } + if (_x.Support != _y.Support) + { + return false; + } + } + return true; + } + public int GetHashCode([DisallowNull] DrawingExcavatorEmpty? obj) + { + return obj.GetHashCode(); + } +} + + diff --git a/WinFormsAppExcavator/WinFormsAppExcavator/Drawings/ExcavatorCompareByColor.cs b/WinFormsAppExcavator/WinFormsAppExcavator/Drawings/ExcavatorCompareByColor.cs new file mode 100644 index 0000000..7c25567 --- /dev/null +++ b/WinFormsAppExcavator/WinFormsAppExcavator/Drawings/ExcavatorCompareByColor.cs @@ -0,0 +1,36 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace WinFormsAppExcavator.Drawings; +/// +/// сравнение по цвету, скорости и весу +/// +public class ExcavatorCompareByColor : IComparer +{ + public int Compare(DrawingExcavatorEmpty? x, DrawingExcavatorEmpty? y) + { + if (x == null || x.EntityExcavatorEmpty == null) + { + return 1; + } + + if (y == null || y.EntityExcavatorEmpty == null) + { + return -1; + } + var bodycolorCompare = x.EntityExcavatorEmpty.BodyColor.Name.CompareTo(y.EntityExcavatorEmpty.BodyColor.Name); + if (bodycolorCompare != 0) + { + return bodycolorCompare; + } + var speedCompare = x.EntityExcavatorEmpty.Speed.CompareTo(y.EntityExcavatorEmpty.Speed); + if (speedCompare != 0) + { + return speedCompare; + } + return x.EntityExcavatorEmpty.Weight.CompareTo(y.EntityExcavatorEmpty.Weight); + } +} diff --git a/WinFormsAppExcavator/WinFormsAppExcavator/Drawings/ExcavatorCompareByType.cs b/WinFormsAppExcavator/WinFormsAppExcavator/Drawings/ExcavatorCompareByType.cs new file mode 100644 index 0000000..b85a3c5 --- /dev/null +++ b/WinFormsAppExcavator/WinFormsAppExcavator/Drawings/ExcavatorCompareByType.cs @@ -0,0 +1,34 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace WinFormsAppExcavator.Drawings; +/// +/// Сравнение по типу, скорости, весу +/// +public class ExcavatorCompareByType : IComparer +{ + public int Compare(DrawingExcavatorEmpty? x, DrawingExcavatorEmpty? y) + { + if (x == null || x.EntityExcavatorEmpty == null) + { + return 1; + } + if (y == null || y.EntityExcavatorEmpty == null) + { + return -1; + } + if (x.GetType().Name != y.GetType().Name) + { + return x.GetType().Name.CompareTo(y.GetType().Name); + } + var speedCompare = x.EntityExcavatorEmpty.Speed.CompareTo(y.EntityExcavatorEmpty.Speed); + if (speedCompare != 0) + { + return speedCompare; + } + return x.EntityExcavatorEmpty.Weight.CompareTo(y.EntityExcavatorEmpty.Weight); + } +} diff --git a/WinFormsAppExcavator/WinFormsAppExcavator/Exception/ObjectIsEqualException.cs b/WinFormsAppExcavator/WinFormsAppExcavator/Exception/ObjectIsEqualException.cs new file mode 100644 index 0000000..02c6b4f --- /dev/null +++ b/WinFormsAppExcavator/WinFormsAppExcavator/Exception/ObjectIsEqualException.cs @@ -0,0 +1,16 @@ +using System.Runtime.Serialization; + +namespace ProjectWarmlyShip.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) { } +} diff --git a/WinFormsAppExcavator/WinFormsAppExcavator/FormExcavatorCollection.Designer.cs b/WinFormsAppExcavator/WinFormsAppExcavator/FormExcavatorCollection.Designer.cs index 7a7d61f..f91313f 100644 --- a/WinFormsAppExcavator/WinFormsAppExcavator/FormExcavatorCollection.Designer.cs +++ b/WinFormsAppExcavator/WinFormsAppExcavator/FormExcavatorCollection.Designer.cs @@ -52,6 +52,8 @@ loadToolStripMenuItem = new ToolStripMenuItem(); saveFileDialog = new SaveFileDialog(); openFileDialog = new OpenFileDialog(); + buttonSortByType = new Button(); + buttonSortByColor = new Button(); groupBoxTools.SuspendLayout(); panelCompanyTools.SuspendLayout(); panelStorage.SuspendLayout(); @@ -68,13 +70,15 @@ groupBoxTools.Dock = DockStyle.Right; groupBoxTools.Location = new Point(642, 28); groupBoxTools.Name = "groupBoxTools"; - groupBoxTools.Size = new Size(220, 491); + groupBoxTools.Size = new Size(220, 555); groupBoxTools.TabIndex = 0; groupBoxTools.TabStop = false; groupBoxTools.Text = "Инструменты"; // // panelCompanyTools // + panelCompanyTools.Controls.Add(buttonSortByType); + panelCompanyTools.Controls.Add(buttonSortByColor); panelCompanyTools.Controls.Add(maskedTextBox); panelCompanyTools.Controls.Add(buttonAddExcavatorEmpty); panelCompanyTools.Controls.Add(buttonGoToCheck); @@ -82,9 +86,9 @@ panelCompanyTools.Controls.Add(buttonRefresh); panelCompanyTools.Dock = DockStyle.Bottom; panelCompanyTools.Enabled = false; - panelCompanyTools.Location = new Point(3, 314); + panelCompanyTools.Location = new Point(3, 319); panelCompanyTools.Name = "panelCompanyTools"; - panelCompanyTools.Size = new Size(214, 174); + panelCompanyTools.Size = new Size(214, 233); panelCompanyTools.TabIndex = 9; // // maskedTextBox @@ -110,7 +114,7 @@ // buttonGoToCheck // buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonGoToCheck.Location = new Point(6, 107); + buttonGoToCheck.Location = new Point(8, 107); buttonGoToCheck.Name = "buttonGoToCheck"; buttonGoToCheck.Size = new Size(206, 29); buttonGoToCheck.TabIndex = 5; @@ -121,7 +125,7 @@ // buttonRemoveExcavator // buttonRemoveExcavator.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonRemoveExcavator.Location = new Point(5, 71); + buttonRemoveExcavator.Location = new Point(8, 71); buttonRemoveExcavator.Name = "buttonRemoveExcavator"; buttonRemoveExcavator.Size = new Size(206, 30); buttonRemoveExcavator.TabIndex = 4; @@ -132,7 +136,7 @@ // buttonRefresh // buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonRefresh.Location = new Point(3, 142); + buttonRefresh.Location = new Point(8, 142); buttonRefresh.Name = "buttonRefresh"; buttonRefresh.Size = new Size(206, 27); buttonRefresh.TabIndex = 6; @@ -248,7 +252,7 @@ pictureBox.Dock = DockStyle.Fill; pictureBox.Location = new Point(0, 28); pictureBox.Name = "pictureBox"; - pictureBox.Size = new Size(642, 491); + pictureBox.Size = new Size(642, 555); pictureBox.TabIndex = 1; pictureBox.TabStop = false; // @@ -293,11 +297,33 @@ // openFileDialog.Filter = "txt file | *.txt"; // + // buttonSortByType + // + buttonSortByType.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + buttonSortByType.Location = new Point(5, 175); + buttonSortByType.Name = "buttonSortByType"; + buttonSortByType.Size = new Size(206, 29); + buttonSortByType.TabIndex = 7; + buttonSortByType.Text = "Сортировка по типу"; + buttonSortByType.UseVisualStyleBackColor = true; + buttonSortByType.Click += buttonSortByType_Click; + // + // buttonSortByColor + // + buttonSortByColor.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + buttonSortByColor.Location = new Point(6, 206); + buttonSortByColor.Name = "buttonSortByColor"; + buttonSortByColor.Size = new Size(206, 27); + buttonSortByColor.TabIndex = 8; + buttonSortByColor.Text = "Сортировка по цвету"; + buttonSortByColor.UseVisualStyleBackColor = true; + buttonSortByColor.Click += buttonSortByColor_Click; + // // FormExcavatorCollection // AutoScaleDimensions = new SizeF(8F, 20F); AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(862, 519); + ClientSize = new Size(862, 583); Controls.Add(pictureBox); Controls.Add(groupBoxTools); Controls.Add(menuStrip); @@ -342,5 +368,7 @@ private ToolStripMenuItem loadToolStripMenuItem; private SaveFileDialog saveFileDialog; private OpenFileDialog openFileDialog; + private Button buttonSortByType; + private Button buttonSortByColor; } } \ No newline at end of file diff --git a/WinFormsAppExcavator/WinFormsAppExcavator/FormExcavatorCollection.cs b/WinFormsAppExcavator/WinFormsAppExcavator/FormExcavatorCollection.cs index 2790486..e968b6b 100644 --- a/WinFormsAppExcavator/WinFormsAppExcavator/FormExcavatorCollection.cs +++ b/WinFormsAppExcavator/WinFormsAppExcavator/FormExcavatorCollection.cs @@ -1,4 +1,5 @@ using Microsoft.Extensions.Logging; +using ProjectWarmlyShip.Exceptions; using System.Windows.Forms; using WinFormsAppExcavator.CollectionGenericObjects; using WinFormsAppExcavator.Drawings; @@ -24,7 +25,7 @@ public partial class FormExcavatorCollection : Form /// /// Конструктор /// - public FormExcavatorCollection(ILogger logger) + public FormExcavatorCollection(ILogger logger) { InitializeComponent(); _storageCollection = new(); @@ -75,13 +76,19 @@ public partial class FormExcavatorCollection : Form catch (ObjectNotFoundException) { } catch (CollectionOverflowException ex) { - MessageBox.Show("Не удалось добавить объект"); + MessageBox.Show("Не удалось добавить объект1"); _logger.LogError("Ошибка: {Message}", ex.Message); } - catch (PositionOutOfCollectionException ex) { + catch (PositionOutOfCollectionException ex) + { MessageBox.Show("Выход за границы коллекции"); _logger.LogError("Ошибка: {Message}", ex.Message); } + catch (ObjectIsEqualException ex) + { + MessageBox.Show("Не удалось добавить объект"); + _logger.LogError("Ошибка: {Message}", ex.Message); + } } /// /// Удаление объекта @@ -210,7 +217,7 @@ public partial class FormExcavatorCollection : 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); @@ -283,7 +290,7 @@ public partial class FormExcavatorCollection : Form { if (saveFileDialog.ShowDialog() == DialogResult.OK) { - try + try { _storageCollection.SaveData(saveFileDialog.FileName); MessageBox.Show("Сохранение прошло успешно", @@ -291,7 +298,7 @@ public partial class FormExcavatorCollection : Form _logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName); } - catch(Exception ex) + catch (Exception ex) { MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); _logger.LogError("Ошибка: {Message}", ex.Message); @@ -324,6 +331,38 @@ public partial class FormExcavatorCollection : Form } } + /// + /// Сортировка по типу + /// + /// + /// + private void buttonSortByType_Click(object sender, EventArgs e) + { + CompareExcavators(new ExcavatorCompareByType()); + } + /// + /// Cортировка по цвету + /// + /// + /// + private void buttonSortByColor_Click(object sender, EventArgs e) + { + CompareExcavators(new ExcavatorCompareByColor()); + } + /// + /// Сортировка по сравнителю + /// + /// Сравнитель объектов + private void CompareExcavators(IComparer comparer) + { + if (_company == null) + { + return; + } + _company.Sort(comparer); + pictureBox.Image = _company.Show(); + } + } diff --git a/WinFormsAppExcavator/WinFormsAppExcavator/FormExcavatorCollection.resx b/WinFormsAppExcavator/WinFormsAppExcavator/FormExcavatorCollection.resx index 0d57ea8..49bef99 100644 --- a/WinFormsAppExcavator/WinFormsAppExcavator/FormExcavatorCollection.resx +++ b/WinFormsAppExcavator/WinFormsAppExcavator/FormExcavatorCollection.resx @@ -127,6 +127,6 @@ 310, 17 - 61 + 123 \ No newline at end of file