From 6c87b978a6bc24aa609c562b873462ae72ddc7bc Mon Sep 17 00:00:00 2001 From: insideq Date: Sun, 12 May 2024 22:08:56 +0400 Subject: [PATCH 1/2] =?UTF-8?q?=D0=9B=D0=B0=D0=B1=D0=BE=D1=80=D0=B0=D1=82?= =?UTF-8?q?=D0=BE=D1=80=D0=BD=D0=B0=D1=8F=20=D1=80=D0=B0=D0=B1=D0=BE=D1=82?= =?UTF-8?q?=D0=B0=20=E2=84=968?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../AbstractCompany.cs | 8 ++- .../CollectionInfo.cs | 72 +++++++++++++++++++ .../ICollectionGenericObjects.cs | 16 ++++- .../ListGenericObjects.cs | 21 +++++- .../MassiveGenericObjects.cs | 27 ++++++- .../StorageCollection.cs | 44 ++++++------ .../DrawningExcavatorCompareByColor.cs | 37 ++++++++++ .../DrawningExcavatorCompareByType.cs | 34 +++++++++ .../Drawnings/DrawningExcavatorEqutables.cs | 72 +++++++++++++++++++ .../CollectionAlreadyExistsException.cs | 17 +++++ .../PositionOutOfCollectionException.cs | 3 + .../FormBulldozerCollection.Designer.cs | 36 ++++++++-- .../FormBulldozerCollection.cs | 37 +++++++++- 13 files changed, 384 insertions(+), 40 deletions(-) create mode 100644 ProjectExcavator/ProjectExcavator/CollectionGenericObjects/CollectionInfo.cs create mode 100644 ProjectExcavator/ProjectExcavator/Drawnings/DrawningExcavatorCompareByColor.cs create mode 100644 ProjectExcavator/ProjectExcavator/Drawnings/DrawningExcavatorCompareByType.cs create mode 100644 ProjectExcavator/ProjectExcavator/Drawnings/DrawningExcavatorEqutables.cs create mode 100644 ProjectExcavator/ProjectExcavator/Exceptions/CollectionAlreadyExistsException.cs diff --git a/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/AbstractCompany.cs b/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/AbstractCompany.cs index e6bf78f..d8227b8 100644 --- a/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/AbstractCompany.cs +++ b/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/AbstractCompany.cs @@ -59,7 +59,7 @@ public abstract class AbstractCompany /// public static int operator +(AbstractCompany company, DrawningBulldozer bulldozer) { - return company._collection.Insert(bulldozer); + return company._collection.Insert(bulldozer, new DrawningExcavatorEqutables()); } /// @@ -103,6 +103,12 @@ public abstract class AbstractCompany return bitmap; } + /// + /// Сортировка + /// + /// Сравниватель объектов + public void Sort(IComparer comparer) => _collection?.CollectionSort(comparer); + /// /// Вывод фона /// diff --git a/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/CollectionInfo.cs b/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/CollectionInfo.cs new file mode 100644 index 0000000..9a4ad73 --- /dev/null +++ b/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/CollectionInfo.cs @@ -0,0 +1,72 @@ +namespace ProjectExcavator.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(); + } +} diff --git a/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/ICollectionGenericObjects.cs b/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/ICollectionGenericObjects.cs index eb0354e..f0b6a0d 100644 --- a/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/ICollectionGenericObjects.cs +++ b/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/ICollectionGenericObjects.cs @@ -1,4 +1,6 @@ -namespace ProjectExcavator.CollectionGenericObjects; +using ProjectExcavator.Drawnings; + +namespace ProjectExcavator.CollectionGenericObjects; /// /// Интерфейс описания действий для набора хранимых объектов @@ -21,16 +23,18 @@ public interface ICollectionGenericObjects /// Добавление элемента в коллекцию /// /// Добавляемый объект + /// Сравнение двух объектов /// true - вставка прошла успешно, false - вставка не удалась - int Insert(T obj); + int Insert(T obj, IEqualityComparer? comparer = null); /// /// Добавление элемента в коллекцию на конкретную позицию /// /// Добавляемый элемент /// Позиция + /// Сравнение двух объектов /// 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); } diff --git a/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/ListGenericObjects.cs b/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/ListGenericObjects.cs index 337767b..8128aae 100644 --- a/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/ListGenericObjects.cs +++ b/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/ListGenericObjects.cs @@ -1,4 +1,4 @@ - +using ProjectExcavator.Drawnings; using ProjectExcavator.Exceptions; namespace ProjectExcavator.CollectionGenericObjects; @@ -39,8 +39,13 @@ public class ListGenericObjects : ICollectionGenericObjects return _collection[position]; } - public int Insert(T obj) + public int Insert(T obj, IEqualityComparer? comparer = null) { + // TODO выброс ошибки, если такой объект есть в коллекции + if (comparer != null && _collection.Contains(obj)) + { + throw new CollectionAlreadyExistsException(); + } // проверка, что не превышено максимальное количество элементов if (_collection.Count >= _maxCount) { @@ -51,8 +56,13 @@ public class ListGenericObjects : ICollectionGenericObjects return _maxCount; } - public int Insert(T obj, int position) + public int Insert(T obj, int position, IEqualityComparer? comparer = null) { + // TODO выброс ошибки, если такой объект есть в коллекции + if (comparer != null && _collection.Contains(obj)) + { + throw new CollectionAlreadyExistsException(); + } // проверка, что не превышено максимальное количество элементов if (Count >= _maxCount) throw new CollectionOverflowException(_maxCount); @@ -83,4 +93,9 @@ public class ListGenericObjects : ICollectionGenericObjects yield return _collection[i]; } } + + public void CollectionSort(IComparer comparer) + { + _collection.Sort(comparer); + } } diff --git a/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/MassiveGenericObjects.cs b/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/MassiveGenericObjects.cs index 1949d54..4837898 100644 --- a/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/MassiveGenericObjects.cs @@ -1,4 +1,5 @@  +using ProjectExcavator.Drawnings; using ProjectExcavator.Exceptions; namespace ProjectExcavator.CollectionGenericObjects; @@ -60,8 +61,13 @@ public class MassiveGenericObjects : ICollectionGenericObjects return _collection[position]; } - public int Insert(T obj) + public int Insert(T obj, IEqualityComparer? comparer = null) { + // TODO выброс ошибки, если такой объект есть в коллекции + if (comparer != null && _collection.Contains(obj)) + { + throw new CollectionAlreadyExistsException(); + } // вставка в свободное место набора int index = 0; while (index < _collection.Length) @@ -76,8 +82,15 @@ 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) { + + // TODO выброс ошибки, если такой объект есть в коллекции + if (comparer != null && _collection.Contains(obj)) + { + throw new CollectionAlreadyExistsException(); + } + // проверка позиции if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position); @@ -138,4 +151,14 @@ public class MassiveGenericObjects : ICollectionGenericObjects yield return _collection[i]; } } + + public void CollectionSort(IComparer comparer) + { + List lst = [.. _collection]; + lst.Sort(comparer.Compare); + for (int i = 0; i < _collection.Length; ++i) + { + _collection[i] = lst[i]; + } + } } diff --git a/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/StorageCollection.cs b/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/StorageCollection.cs index fa095bb..9e1d604 100644 --- a/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/StorageCollection.cs +++ b/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/StorageCollection.cs @@ -13,12 +13,12 @@ public class StorageCollection /// /// Словарь (хранилище) с коллекциями /// - readonly Dictionary> _storages; + readonly Dictionary> _storages; /// /// Возвращение списка названий коллекций /// - public List Keys => _storages.Keys.ToList(); + public List Keys => _storages.Keys.ToList(); /// /// Ключевое слово, с которого должен начинаться файл @@ -40,7 +40,7 @@ public class StorageCollection /// public StorageCollection() { - _storages = new Dictionary>(); + _storages = new Dictionary>(); } /// @@ -51,18 +51,19 @@ public class StorageCollection public void AddCollection(string name, CollectionType collectionType) { // проверка, что name не пустой и нет в словаре записи с таким ключом - if (string.IsNullOrEmpty(name) || _storages.ContainsKey(name)) + if (string.IsNullOrEmpty(name) || _storages.ContainsKey(new CollectionInfo(name, collectionType, string.Empty))) { + MessageBox.Show("Коллекция с таким именем уже существует", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } // прописать логику для добавления if (collectionType == CollectionType.List) { - _storages.Add(name, new ListGenericObjects()); + _storages.Add(new CollectionInfo(name, collectionType, string.Empty), new ListGenericObjects()); } if (collectionType == CollectionType.Massive) { - _storages.Add(name, new MassiveGenericObjects()); + _storages.Add(new CollectionInfo(name, collectionType, string.Empty), new MassiveGenericObjects()); } } @@ -73,8 +74,8 @@ public class StorageCollection public void DelCollection(string name) { // прописать логику для удаления коллекции - if (!_storages.ContainsKey(name)) return; - _storages.Remove(name); + if (!_storages.ContainsKey(new CollectionInfo(name, CollectionType.None, string.Empty))) return; + _storages.Remove(new CollectionInfo(name, CollectionType.None, string.Empty)); } /// @@ -87,9 +88,9 @@ public class StorageCollection get { // продумать логику получения объекта - if (_storages.ContainsKey((string)name)) + if (_storages.ContainsKey(new CollectionInfo(name, CollectionType.None, string.Empty))) { - return _storages[name]; + return _storages[new CollectionInfo(name, CollectionType.None, string.Empty)]; } return null; } @@ -114,7 +115,7 @@ public class StorageCollection using (StreamWriter writer = new StreamWriter(filename)) { writer.Write(_collectionKey); - foreach (KeyValuePair> value in _storages) + foreach (KeyValuePair> value in _storages) { writer.Write(Environment.NewLine); // не сохраняем пустые коллекции @@ -125,8 +126,6 @@ public class StorageCollection writer.Write(value.Key); writer.Write(_separatorForKeyValue); - writer.Write(value.Value.GetCollectionType); - writer.Write(_separatorForKeyValue); writer.Write(value.Value.MaxCount); writer.Write(_separatorForKeyValue); @@ -176,21 +175,18 @@ public class StorageCollection while ((strs = reader.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); - if (collection == null) - { - throw new Exception("Не удалось создать коллекцию"); - } + CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(record[0]) ?? + throw new Exception("Не удалось определить информацию коллекции:" + record[0]); + ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionInfo.CollectionType) ?? + throw new Exception("Не удалось определить тип коллекции:" + record[1]); + collection.MaxCount = Convert.ToInt32(record[1]); - collection.MaxCount = Convert.ToInt32(record[2]); - - string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); + string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); foreach (string elem in set) { if (elem?.CreateDrawningBulldozer() is T bulldozer) @@ -209,7 +205,7 @@ public class StorageCollection } } - _storages.Add(record[0], collection); + _storages.Add(collectionInfo, collection); } } } diff --git a/ProjectExcavator/ProjectExcavator/Drawnings/DrawningExcavatorCompareByColor.cs b/ProjectExcavator/ProjectExcavator/Drawnings/DrawningExcavatorCompareByColor.cs new file mode 100644 index 0000000..c4a4922 --- /dev/null +++ b/ProjectExcavator/ProjectExcavator/Drawnings/DrawningExcavatorCompareByColor.cs @@ -0,0 +1,37 @@ +using ProjectExcavator.Entities; + +namespace ProjectExcavator.Drawnings; + +/// +/// Сравнение по цвету, скорости, весу +/// +public class DrawningExcavatorCompareByColor : IComparer +{ + public int Compare(DrawningBulldozer? x, DrawningBulldozer? y) + { + // TODO прописать логику сравнения по цветам, скорости, весу + if (x == null || x.EntityBulldozer == null) + { + return 1; + } + + if (y == null || y.EntityBulldozer == null) + { + return -1; + } + + if (x.EntityBulldozer.BodyColor != y.EntityBulldozer.BodyColor) + { + return x.EntityBulldozer.BodyColor.Name.CompareTo(y.EntityBulldozer.BodyColor.Name); + } + + var speedCompare = x.EntityBulldozer.Speed.CompareTo(y.EntityBulldozer.Speed); + + if (speedCompare != 0) + { + return speedCompare; + } + + return x.EntityBulldozer.Weight.CompareTo(y.EntityBulldozer.Weight); + } +} diff --git a/ProjectExcavator/ProjectExcavator/Drawnings/DrawningExcavatorCompareByType.cs b/ProjectExcavator/ProjectExcavator/Drawnings/DrawningExcavatorCompareByType.cs new file mode 100644 index 0000000..5a0f024 --- /dev/null +++ b/ProjectExcavator/ProjectExcavator/Drawnings/DrawningExcavatorCompareByType.cs @@ -0,0 +1,34 @@ +namespace ProjectExcavator.Drawnings; + +/// +/// Сравнение по типу, скорости, весу +/// +public class DrawningExcavatorCompareByType : IComparer +{ + public int Compare(DrawningBulldozer? x, DrawningBulldozer? y) + { + if (x == null || x.EntityBulldozer == null) + { + return 1; + } + + if (y == null || y.EntityBulldozer == null) + { + return -1; + } + + if (x.GetType().Name != y.GetType().Name) + { + return x.GetType().Name.CompareTo(y.GetType().Name); + } + + var speedCompare = x.EntityBulldozer.Speed.CompareTo(y.EntityBulldozer.Speed); + + if (speedCompare != 0) + { + return speedCompare; + } + + return x.EntityBulldozer.Weight.CompareTo(y.EntityBulldozer.Weight); + } +} diff --git a/ProjectExcavator/ProjectExcavator/Drawnings/DrawningExcavatorEqutables.cs b/ProjectExcavator/ProjectExcavator/Drawnings/DrawningExcavatorEqutables.cs new file mode 100644 index 0000000..9802cb2 --- /dev/null +++ b/ProjectExcavator/ProjectExcavator/Drawnings/DrawningExcavatorEqutables.cs @@ -0,0 +1,72 @@ +using ProjectExcavator.Entities; +using System.Diagnostics.CodeAnalysis; + +namespace ProjectExcavator.Drawnings; + +/// +/// Реализация сравнения двух объектов класса-прорисовки +/// +public class DrawningExcavatorEqutables : IEqualityComparer +{ + public bool Equals(DrawningBulldozer? x, DrawningBulldozer? y) + { + if (x == null || x.EntityBulldozer == null) + { + return false; + } + + if (y == null || y.EntityBulldozer == null) + { + return false; + } + + if (x.GetType().Name != y.GetType().Name) + { + return false; + } + + if (x.EntityBulldozer.Speed != y.EntityBulldozer.Speed) + { + return false; + } + + if (x.EntityBulldozer.Weight != y.EntityBulldozer.Weight) + { + return false; + } + + if (x.EntityBulldozer.BodyColor != y.EntityBulldozer.BodyColor) + { + return false; + } + + if (x is DrawningExcavator && y is DrawningExcavator) + { + // TODO доделать логику сравнения дополнительных параметров + EntityExcavator xExcavator = (EntityExcavator)x.EntityBulldozer; + EntityExcavator yExcavator = (EntityExcavator)y.EntityBulldozer; + + if(xExcavator.AdditionalColor != yExcavator.AdditionalColor) + { + return false; + } + + if (xExcavator.Ladle != yExcavator.Ladle) + { + return false; + } + + if (xExcavator.Prop != yExcavator.Prop) + { + return false; + } + } + + return true; + } + + public int GetHashCode([DisallowNull] DrawningBulldozer obj) + { + return obj.GetHashCode(); + } +} diff --git a/ProjectExcavator/ProjectExcavator/Exceptions/CollectionAlreadyExistsException.cs b/ProjectExcavator/ProjectExcavator/Exceptions/CollectionAlreadyExistsException.cs new file mode 100644 index 0000000..9476edf --- /dev/null +++ b/ProjectExcavator/ProjectExcavator/Exceptions/CollectionAlreadyExistsException.cs @@ -0,0 +1,17 @@ +using ProjectExcavator.CollectionGenericObjects; +using System.Runtime.Serialization; + +namespace ProjectExcavator.Exceptions; + +/// +/// Класс, описывающий ошибку повторяющегося элемента в коллекции +/// +[Serializable] +internal class CollectionAlreadyExistsException : ApplicationException +{ + public CollectionAlreadyExistsException(CollectionInfo collectionInfo) : base("В коллекции уже есть такой элемент: " + collectionInfo) { } + public CollectionAlreadyExistsException() : base() { } + public CollectionAlreadyExistsException(string message) : base(message) { } + public CollectionAlreadyExistsException(string message, Exception exception) : base(message, exception) { } + protected CollectionAlreadyExistsException(SerializationInfo info, StreamingContext context) : base(info, context) { } +} diff --git a/ProjectExcavator/ProjectExcavator/Exceptions/PositionOutOfCollectionException.cs b/ProjectExcavator/ProjectExcavator/Exceptions/PositionOutOfCollectionException.cs index f520eb4..2355d25 100644 --- a/ProjectExcavator/ProjectExcavator/Exceptions/PositionOutOfCollectionException.cs +++ b/ProjectExcavator/ProjectExcavator/Exceptions/PositionOutOfCollectionException.cs @@ -2,6 +2,9 @@ namespace ProjectExcavator.Exceptions; +/// +/// Класс, описывающий ошибку, что позиция вышла за границы коллекции +/// [Serializable] internal class PositionOutOfCollectionException : ApplicationException { diff --git a/ProjectExcavator/ProjectExcavator/FormBulldozerCollection.Designer.cs b/ProjectExcavator/ProjectExcavator/FormBulldozerCollection.Designer.cs index 243324f..ee3ce00 100644 --- a/ProjectExcavator/ProjectExcavator/FormBulldozerCollection.Designer.cs +++ b/ProjectExcavator/ProjectExcavator/FormBulldozerCollection.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(774, 24); groupBoxTools.Name = "groupBoxTools"; - groupBoxTools.Size = new Size(187, 576); + groupBoxTools.Size = new Size(187, 671); groupBoxTools.TabIndex = 0; groupBoxTools.TabStop = false; groupBoxTools.Text = "Инструменты"; // // panelCompanyTools // + panelCompanyTools.Controls.Add(buttonSortByType); + panelCompanyTools.Controls.Add(buttonSortByColor); panelCompanyTools.Controls.Add(buttonGoToCheck); panelCompanyTools.Controls.Add(buttonAddBulldozer); panelCompanyTools.Controls.Add(buttonRemoveCar); @@ -84,7 +88,7 @@ panelCompanyTools.Enabled = false; panelCompanyTools.Location = new Point(3, 328); panelCompanyTools.Name = "panelCompanyTools"; - panelCompanyTools.Size = new Size(181, 245); + panelCompanyTools.Size = new Size(181, 340); panelCompanyTools.TabIndex = 9; // // buttonGoToCheck @@ -249,7 +253,7 @@ pictureBox.Dock = DockStyle.Fill; pictureBox.Location = new Point(0, 24); pictureBox.Name = "pictureBox"; - pictureBox.Size = new Size(774, 576); + pictureBox.Size = new Size(774, 671); 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(12, 245); + buttonSortByType.Name = "buttonSortByType"; + buttonSortByType.Size = new Size(160, 42); + 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(12, 293); + buttonSortByColor.Name = "buttonSortByColor"; + buttonSortByColor.Size = new Size(160, 42); + buttonSortByColor.TabIndex = 8; + buttonSortByColor.Text = "Сортировка по цвету"; + buttonSortByColor.UseVisualStyleBackColor = true; + buttonSortByColor.Click += ButtonSortByColor_Click; + // // FormBulldozerCollection // AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(961, 600); + ClientSize = new Size(961, 695); 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/ProjectExcavator/ProjectExcavator/FormBulldozerCollection.cs b/ProjectExcavator/ProjectExcavator/FormBulldozerCollection.cs index 5cfbb70..4eecfb3 100644 --- a/ProjectExcavator/ProjectExcavator/FormBulldozerCollection.cs +++ b/ProjectExcavator/ProjectExcavator/FormBulldozerCollection.cs @@ -235,7 +235,7 @@ public partial class FormBulldozerCollection : 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); @@ -290,7 +290,7 @@ public partial class FormBulldozerCollection : Form MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); _logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName); } - catch(Exception ex) + catch (Exception ex) { MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); _logger.LogError("Ошибка: {Message}", ex.Message); @@ -314,11 +314,42 @@ public partial class FormBulldozerCollection : Form RefreshListBoxItems(); _logger.LogInformation("Загрузка из файла: {filename}", openFileDialog.FileName); } - catch(Exception ex) + catch (Exception ex) { MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); _logger.LogError("Ошибка: {Message}", ex.Message); } } } + + /// + /// Сортировка по типу + /// + /// + /// + private void ButtonSortByType_Click(object sender, EventArgs e) + { + CompareExcavators(new DrawningExcavatorCompareByType()); + } + + /// + /// Сортировка по цвету + /// + /// + /// + private void ButtonSortByColor_Click(object sender, EventArgs e) + { + CompareExcavators(new DrawningExcavatorCompareByColor()); + } + + private void CompareExcavators(IComparer comparer) + { + if (_company == null) + { + return; + } + + _company.Sort(comparer); + pictureBox.Image = _company.Show(); + } } -- 2.25.1 From 12f8e6c8288460958299a93e0fa91ddfaa3d9b9b Mon Sep 17 00:00:00 2001 From: insideq Date: Thu, 16 May 2024 11:36:31 +0400 Subject: [PATCH 2/2] =?UTF-8?q?=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=B8=D0=BB?= =?UTF-8?q?=20=D0=BF=D1=80=D0=BE=D0=B2=D0=B5=D1=80=D0=BA=D0=B8=20=D0=B8=20?= =?UTF-8?q?=D0=BE=D0=B1=D1=80=D0=B0=D0=B1=D0=BE=D1=82=D0=BA=D1=83=20=D0=BE?= =?UTF-8?q?=D1=88=D0=B8=D0=B1=D0=BA=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../CollectionGenericObjects/ICollectionGenericObjects.cs | 4 ++-- .../CollectionGenericObjects/ListGenericObjects.cs | 8 ++++---- .../CollectionGenericObjects/MassiveGenericObjects.cs | 8 ++++---- .../Exceptions/CollectionAlreadyExistsException.cs | 2 +- .../ProjectExcavator/FormBulldozerCollection.cs | 5 +++++ 5 files changed, 16 insertions(+), 11 deletions(-) diff --git a/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/ICollectionGenericObjects.cs b/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/ICollectionGenericObjects.cs index f0b6a0d..81be154 100644 --- a/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/ICollectionGenericObjects.cs +++ b/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/ICollectionGenericObjects.cs @@ -25,7 +25,7 @@ public interface ICollectionGenericObjects /// Добавляемый объект /// Сравнение двух объектов /// true - вставка прошла успешно, false - вставка не удалась - int Insert(T obj, IEqualityComparer? comparer = null); + int Insert(T obj, IEqualityComparer? comparer = null); /// /// Добавление элемента в коллекцию на конкретную позицию @@ -34,7 +34,7 @@ public interface ICollectionGenericObjects /// Позиция /// Сравнение двух объектов /// true - вставка прошла успешно, false - вставка не удалась - int Insert(T obj, int position, IEqualityComparer? comparer = null); + int Insert(T obj, int position, IEqualityComparer? comparer = null); /// /// Удаление объекта из коллекции с конкретной позиции diff --git a/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/ListGenericObjects.cs b/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/ListGenericObjects.cs index 8128aae..4216665 100644 --- a/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/ListGenericObjects.cs +++ b/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/ListGenericObjects.cs @@ -39,10 +39,10 @@ public class ListGenericObjects : ICollectionGenericObjects return _collection[position]; } - public int Insert(T obj, IEqualityComparer? comparer = null) + public int Insert(T obj, IEqualityComparer? comparer = null) { // TODO выброс ошибки, если такой объект есть в коллекции - if (comparer != null && _collection.Contains(obj)) + if (comparer != null && _collection.Contains(obj, comparer)) { throw new CollectionAlreadyExistsException(); } @@ -56,10 +56,10 @@ public class ListGenericObjects : ICollectionGenericObjects return _maxCount; } - public int Insert(T obj, int position, IEqualityComparer? comparer = null) + public int Insert(T obj, int position, IEqualityComparer? comparer = null) { // TODO выброс ошибки, если такой объект есть в коллекции - if (comparer != null && _collection.Contains(obj)) + if (comparer != null && _collection.Contains(obj, comparer)) { throw new CollectionAlreadyExistsException(); } diff --git a/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/MassiveGenericObjects.cs b/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/MassiveGenericObjects.cs index 4837898..52b94b5 100644 --- a/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/MassiveGenericObjects.cs @@ -61,10 +61,10 @@ public class MassiveGenericObjects : ICollectionGenericObjects return _collection[position]; } - public int Insert(T obj, IEqualityComparer? comparer = null) + public int Insert(T obj, IEqualityComparer? comparer = null) { // TODO выброс ошибки, если такой объект есть в коллекции - if (comparer != null && _collection.Contains(obj)) + if (comparer != null && _collection.Contains(obj, comparer)) { throw new CollectionAlreadyExistsException(); } @@ -82,11 +82,11 @@ public class MassiveGenericObjects : ICollectionGenericObjects throw new CollectionOverflowException(Count); } - public int Insert(T obj, int position, IEqualityComparer? comparer = null) + public int Insert(T obj, int position, IEqualityComparer? comparer = null) { // TODO выброс ошибки, если такой объект есть в коллекции - if (comparer != null && _collection.Contains(obj)) + if (comparer != null && _collection.Contains(obj, comparer)) { throw new CollectionAlreadyExistsException(); } diff --git a/ProjectExcavator/ProjectExcavator/Exceptions/CollectionAlreadyExistsException.cs b/ProjectExcavator/ProjectExcavator/Exceptions/CollectionAlreadyExistsException.cs index 9476edf..bce663e 100644 --- a/ProjectExcavator/ProjectExcavator/Exceptions/CollectionAlreadyExistsException.cs +++ b/ProjectExcavator/ProjectExcavator/Exceptions/CollectionAlreadyExistsException.cs @@ -10,7 +10,7 @@ namespace ProjectExcavator.Exceptions; internal class CollectionAlreadyExistsException : ApplicationException { public CollectionAlreadyExistsException(CollectionInfo collectionInfo) : base("В коллекции уже есть такой элемент: " + collectionInfo) { } - public CollectionAlreadyExistsException() : base() { } + public CollectionAlreadyExistsException() : base("В коллекции уже есть такой элемент") { } public CollectionAlreadyExistsException(string message) : base(message) { } public CollectionAlreadyExistsException(string message, Exception exception) : base(message, exception) { } protected CollectionAlreadyExistsException(SerializationInfo info, StreamingContext context) : base(info, context) { } diff --git a/ProjectExcavator/ProjectExcavator/FormBulldozerCollection.cs b/ProjectExcavator/ProjectExcavator/FormBulldozerCollection.cs index 4eecfb3..9812485 100644 --- a/ProjectExcavator/ProjectExcavator/FormBulldozerCollection.cs +++ b/ProjectExcavator/ProjectExcavator/FormBulldozerCollection.cs @@ -82,6 +82,11 @@ public partial class FormBulldozerCollection : Form MessageBox.Show(ex.Message); _logger.LogError("Ошибка: {Message}", ex.Message); } + catch (CollectionAlreadyExistsException ex) + { + MessageBox.Show(ex.Message); + _logger.LogError("Ошибка: {Message}", ex.Message); + } } private void ButtonRemoveCar_Click(object sender, EventArgs e) -- 2.25.1