From f7e06bd8c40b2652dd04fd75b4d71a17817320fe Mon Sep 17 00:00:00 2001 From: Geo7312 Date: Fri, 7 Jun 2024 22:14:18 +0400 Subject: [PATCH 1/2] =?UTF-8?q?=D0=9B=D0=B0=D0=B1=D0=B0=208=20(=D0=BD?= =?UTF-8?q?=D0=B5=20=D0=B4=D0=BE=D0=B4=D0=B5=D0=BB)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../AbstractCompany.cs | 8 ++- .../CollectionInfo.cs | 72 +++++++++++++++++++ .../ICollectionGenericObjects.cs | 13 +++- .../ListGenericObjects.cs | 26 +++++-- .../MassiveGenericObjects.cs | 25 ++++++- .../StorageCollection.cs | 59 +++++++-------- .../DrawningTrolleyBCompareByColor.cs | 36 ++++++++++ .../DrawningTrolleyBCompareByType.cs | 34 +++++++++ .../Drawnings/DrawningTrolleyBEqutables.cs | 71 ++++++++++++++++++ .../CollectionAlreadyExistsException.cs | 13 ++++ .../PositionOutOfCollectionException.cs | 3 + .../FormTrolleyBCollection.Designer.cs | 48 ++++++++++--- .../FormTrolleyBCollection.cs | 33 ++++++++- 13 files changed, 391 insertions(+), 50 deletions(-) create mode 100644 ProjectTrolleybus/ProjectTrolleybus/CollectionGenericObjects/CollectionInfo.cs create mode 100644 ProjectTrolleybus/ProjectTrolleybus/Drawnings/DrawningTrolleyBCompareByColor.cs create mode 100644 ProjectTrolleybus/ProjectTrolleybus/Drawnings/DrawningTrolleyBCompareByType.cs create mode 100644 ProjectTrolleybus/ProjectTrolleybus/Drawnings/DrawningTrolleyBEqutables.cs create mode 100644 ProjectTrolleybus/ProjectTrolleybus/Exceptions/CollectionAlreadyExistsException.cs diff --git a/ProjectTrolleybus/ProjectTrolleybus/CollectionGenericObjects/AbstractCompany.cs b/ProjectTrolleybus/ProjectTrolleybus/CollectionGenericObjects/AbstractCompany.cs index c067004..b43298e 100644 --- a/ProjectTrolleybus/ProjectTrolleybus/CollectionGenericObjects/AbstractCompany.cs +++ b/ProjectTrolleybus/ProjectTrolleybus/CollectionGenericObjects/AbstractCompany.cs @@ -57,7 +57,7 @@ public abstract class AbstractCompany /// public static int operator +(AbstractCompany company, DrawningTrolleyB trolleyB) { - return company._collection.Insert(trolleyB); + return company._collection.Insert(trolleyB, new DrawningTrolleyBEqutables()); } /// @@ -97,6 +97,12 @@ public abstract class AbstractCompany return bitmap; } + /// + /// Сортировка + /// + /// Сравниватель объектов + public void Sort(IComparer comparer) => _collection?.CollectionSort(comparer); + protected abstract void DrawBackground(Graphics g); protected abstract void SetObjectPosition(); diff --git a/ProjectTrolleybus/ProjectTrolleybus/CollectionGenericObjects/CollectionInfo.cs b/ProjectTrolleybus/ProjectTrolleybus/CollectionGenericObjects/CollectionInfo.cs new file mode 100644 index 0000000..4834ac6 --- /dev/null +++ b/ProjectTrolleybus/ProjectTrolleybus/CollectionGenericObjects/CollectionInfo.cs @@ -0,0 +1,72 @@ +namespace ProjectTrolleybus.CollectionGenericObjects; + +/// +/// Класс, хранящий информацию по коллекции +/// +public class CollectionInfo +{ + /// + /// Название + /// + 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/ProjectTrolleybus/ProjectTrolleybus/CollectionGenericObjects/ICollectionGenericObjects.cs b/ProjectTrolleybus/ProjectTrolleybus/CollectionGenericObjects/ICollectionGenericObjects.cs index e132cea..c51216f 100644 --- a/ProjectTrolleybus/ProjectTrolleybus/CollectionGenericObjects/ICollectionGenericObjects.cs +++ b/ProjectTrolleybus/ProjectTrolleybus/CollectionGenericObjects/ICollectionGenericObjects.cs @@ -1,4 +1,5 @@ -namespace ProjectTrolleybus.CollectionGenericObjects; +using ProjectTrolleybus.Drawnings; +namespace ProjectTrolleybus.CollectionGenericObjects; /// /// Интерфейс описания действий для набора хранимых объектов @@ -22,14 +23,14 @@ public interface ICollectionGenericObjects /// /// /// - 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 +57,10 @@ public interface ICollectionGenericObjects /// Поэлементный вывод элементов коллекции IEnumerable GetItems(); + /// + /// Сортировка коллекции + /// + /// Сравниватель объектов + void CollectionSort(IComparer comparer); + } diff --git a/ProjectTrolleybus/ProjectTrolleybus/CollectionGenericObjects/ListGenericObjects.cs b/ProjectTrolleybus/ProjectTrolleybus/CollectionGenericObjects/ListGenericObjects.cs index 3901045..ade2479 100644 --- a/ProjectTrolleybus/ProjectTrolleybus/CollectionGenericObjects/ListGenericObjects.cs +++ b/ProjectTrolleybus/ProjectTrolleybus/CollectionGenericObjects/ListGenericObjects.cs @@ -1,5 +1,7 @@ -namespace ProjectTrolleybus.CollectionGenericObjects; -using ProjectTrolleybus.Exceptions; +using ProjectTrolleybus.Exceptions; +using ProjectTrolleybus.Drawnings; +namespace ProjectTrolleybus.CollectionGenericObjects; + /// /// Параметризированный набор объектов @@ -42,8 +44,13 @@ public class ListGenericObjects : ICollectionGenericObjects } - 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) { @@ -55,8 +62,14 @@ public class ListGenericObjects : ICollectionGenericObjects } - 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); @@ -89,4 +102,9 @@ public class ListGenericObjects : ICollectionGenericObjects yield return _collection[i]; } } + + public void CollectionSort(IComparer comparer) + { + _collection.Sort(comparer); + } } diff --git a/ProjectTrolleybus/ProjectTrolleybus/CollectionGenericObjects/MassiveGenericObjects.cs b/ProjectTrolleybus/ProjectTrolleybus/CollectionGenericObjects/MassiveGenericObjects.cs index 40b155d..f1e9429 100644 --- a/ProjectTrolleybus/ProjectTrolleybus/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/ProjectTrolleybus/ProjectTrolleybus/CollectionGenericObjects/MassiveGenericObjects.cs @@ -1,4 +1,5 @@ namespace ProjectTrolleybus.CollectionGenericObjects; +using ProjectTrolleybus.Drawnings; using ProjectTrolleybus.Exceptions; /// @@ -61,8 +62,13 @@ public class MassiveGenericObjects : ICollectionGenericObjects } - 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) @@ -78,8 +84,13 @@ public class MassiveGenericObjects : ICollectionGenericObjects } - 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); @@ -143,4 +154,14 @@ public class MassiveGenericObjects : ICollectionGenericObjects } } + 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/ProjectTrolleybus/ProjectTrolleybus/CollectionGenericObjects/StorageCollection.cs b/ProjectTrolleybus/ProjectTrolleybus/CollectionGenericObjects/StorageCollection.cs index b47e772..41874cf 100644 --- a/ProjectTrolleybus/ProjectTrolleybus/CollectionGenericObjects/StorageCollection.cs +++ b/ProjectTrolleybus/ProjectTrolleybus/CollectionGenericObjects/StorageCollection.cs @@ -13,12 +13,12 @@ public class StorageCollection /// /// Словарь (хранилище) с коллекциями /// - private 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>(); } /// @@ -50,17 +50,22 @@ public class StorageCollection /// тип коллецкии public void AddCollection(string name, CollectionType collectionType) { - if (!(collectionType == CollectionType.None) && !_storages.ContainsKey(name)) + // проверка, что name не пустой и нет в словаре записи с таким ключом + if (string.IsNullOrEmpty(name) || _storages.ContainsKey(new CollectionInfo(name, collectionType, string.Empty))) { - if (collectionType == CollectionType.List) - { - _storages.Add(name, new ListGenericObjects()); - } - else if (collectionType == CollectionType.Massive) - { - _storages.Add(name, new MassiveGenericObjects()); - } + MessageBox.Show("Коллекция с таким именем уже существует", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; } + // прописать логику для добавления + if (collectionType == CollectionType.List) + { + _storages.Add(new CollectionInfo(name, collectionType, string.Empty), new ListGenericObjects()); + } + if (collectionType == CollectionType.Massive) + { + _storages.Add(new CollectionInfo(name, collectionType, string.Empty), new MassiveGenericObjects()); + } + } /// @@ -69,7 +74,8 @@ public class StorageCollection /// Название коллекции public void DelCollection(string name) { - if (_storages.ContainsKey(name)) { _storages.Remove(name); } + if (!_storages.ContainsKey(new CollectionInfo(name, CollectionType.None, string.Empty))) return; + _storages.Remove(new CollectionInfo(name, CollectionType.None, string.Empty)); } /// /// Доступ к коллекции @@ -80,9 +86,9 @@ public class StorageCollection { get { - if (_storages.ContainsKey(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; } @@ -108,7 +114,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); // не сохраняем пустые коллекции @@ -119,8 +125,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); @@ -171,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?.CreateDrawningTrolleyB() is T trolleyB) @@ -204,7 +205,7 @@ public class StorageCollection } } - _storages.Add(record[0], collection); + _storages.Add(collectionInfo, collection); } } } diff --git a/ProjectTrolleybus/ProjectTrolleybus/Drawnings/DrawningTrolleyBCompareByColor.cs b/ProjectTrolleybus/ProjectTrolleybus/Drawnings/DrawningTrolleyBCompareByColor.cs new file mode 100644 index 0000000..543d342 --- /dev/null +++ b/ProjectTrolleybus/ProjectTrolleybus/Drawnings/DrawningTrolleyBCompareByColor.cs @@ -0,0 +1,36 @@ +using ProjectTrolleybus.Entities; +namespace ProjectTrolleybus.Drawnings; + +/// +/// Сравнение по цвету, скорости, весу +/// +public class DrawningTrolleyBCompareByColor : IComparer +{ + public int Compare(DrawningTrolleyB? x, DrawningTrolleyB? y) + { + // TODO прописать логику сравнения по цветам, скорости, весу + if (x == null || x.EntityTrolleyB == null) + { + return 1; + } + + if (y == null || y.EntityTrolleyB == null) + { + return -1; + } + + if (x.EntityTrolleyB.BodyColor != y.EntityTrolleyB.BodyColor) + { + return x.EntityTrolleyB.BodyColor.Name.CompareTo(y.EntityTrolleyB.BodyColor.Name); + } + + var speedCompare = x.EntityTrolleyB.Speed.CompareTo(y.EntityTrolleyB.Speed); + + if (speedCompare != 0) + { + return speedCompare; + } + + return x.EntityTrolleyB.Weight.CompareTo(y.EntityTrolleyB.Weight); + } +} diff --git a/ProjectTrolleybus/ProjectTrolleybus/Drawnings/DrawningTrolleyBCompareByType.cs b/ProjectTrolleybus/ProjectTrolleybus/Drawnings/DrawningTrolleyBCompareByType.cs new file mode 100644 index 0000000..9ee2a20 --- /dev/null +++ b/ProjectTrolleybus/ProjectTrolleybus/Drawnings/DrawningTrolleyBCompareByType.cs @@ -0,0 +1,34 @@ +namespace ProjectTrolleybus.Drawnings; + +/// +/// Сравнение по типу, скорости, весу +/// +public class DrawningTrolleyBCompareByType : IComparer +{ + public int Compare(DrawningTrolleyB? x, DrawningTrolleyB? y) + { + if (x == null || x.EntityTrolleyB == null) + { + return 1; + } + + if (y == null || y.EntityTrolleyB == null) + { + return -1; + } + + if (x.GetType().Name != y.GetType().Name) + { + return x.GetType().Name.CompareTo(y.GetType().Name); + } + + var speedCompare = x.EntityTrolleyB.Speed.CompareTo(y.EntityTrolleyB.Speed); + + if (speedCompare != 0) + { + return speedCompare; + } + + return x.EntityTrolleyB.Weight.CompareTo(y.EntityTrolleyB.Weight); + } +} diff --git a/ProjectTrolleybus/ProjectTrolleybus/Drawnings/DrawningTrolleyBEqutables.cs b/ProjectTrolleybus/ProjectTrolleybus/Drawnings/DrawningTrolleyBEqutables.cs new file mode 100644 index 0000000..665de7d --- /dev/null +++ b/ProjectTrolleybus/ProjectTrolleybus/Drawnings/DrawningTrolleyBEqutables.cs @@ -0,0 +1,71 @@ +using System.Diagnostics.CodeAnalysis; +using ProjectTrolleybus.Entities; +namespace ProjectTrolleybus.Drawnings; + +/// +/// Реализация сравнения двух объектов класса-прорисовки +/// +public class DrawningTrolleyBEqutables : IEqualityComparer +{ + public bool Equals(DrawningTrolleyB? x, DrawningTrolleyB? y) + { + if (x == null || x.EntityTrolleyB == null) + { + return false; + } + + if (y == null || y.EntityTrolleyB == null) + { + return false; + } + + if (x.GetType().Name != y.GetType().Name) + { + return false; + } + + if (x.EntityTrolleyB.Speed != y.EntityTrolleyB.Speed) + { + return false; + } + + if (x.EntityTrolleyB.Weight != y.EntityTrolleyB.Weight) + { + return false; + } + + if (x.EntityTrolleyB.BodyColor != y.EntityTrolleyB.BodyColor) + { + return false; + } + + if (x is DrawningTrolleybus && y is DrawningTrolleybus) + { + // TODO доделать логику сравнения дополнительных параметров + EntityTrolleybus xTrolleybus = (EntityTrolleybus)x.EntityTrolleyB; + EntityTrolleybus yTrolleybus = (EntityTrolleybus)y.EntityTrolleyB; + + if (xTrolleybus.AdditionalColor != yTrolleybus.AdditionalColor) + { + return false; + } + + if (xTrolleybus.BatteryCompartment != yTrolleybus.BatteryCompartment) + { + return false; + } + + if (xTrolleybus.Horns != yTrolleybus.Horns) + { + return false; + } + } + + return true; + } + + public int GetHashCode([DisallowNull] DrawningTrolleyB obj) + { + return obj.GetHashCode(); + } +} diff --git a/ProjectTrolleybus/ProjectTrolleybus/Exceptions/CollectionAlreadyExistsException.cs b/ProjectTrolleybus/ProjectTrolleybus/Exceptions/CollectionAlreadyExistsException.cs new file mode 100644 index 0000000..05bb400 --- /dev/null +++ b/ProjectTrolleybus/ProjectTrolleybus/Exceptions/CollectionAlreadyExistsException.cs @@ -0,0 +1,13 @@ +using ProjectTrolleybus.CollectionGenericObjects; +using System.Runtime.Serialization; + +namespace ProjectTrolleybus.Exceptions; + +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/ProjectTrolleybus/ProjectTrolleybus/Exceptions/PositionOutOfCollectionException.cs b/ProjectTrolleybus/ProjectTrolleybus/Exceptions/PositionOutOfCollectionException.cs index cbc806a..270cd03 100644 --- a/ProjectTrolleybus/ProjectTrolleybus/Exceptions/PositionOutOfCollectionException.cs +++ b/ProjectTrolleybus/ProjectTrolleybus/Exceptions/PositionOutOfCollectionException.cs @@ -2,6 +2,9 @@ namespace ProjectTrolleybus.Exceptions; +/// +/// Класс, описывающий ошибку, что позиция вышла за границы коллекции +/// [Serializable] internal class PositionOutOfCollectionException : ApplicationException { diff --git a/ProjectTrolleybus/ProjectTrolleybus/FormTrolleyBCollection.Designer.cs b/ProjectTrolleybus/ProjectTrolleybus/FormTrolleyBCollection.Designer.cs index 495a441..bd79c14 100644 --- a/ProjectTrolleybus/ProjectTrolleybus/FormTrolleyBCollection.Designer.cs +++ b/ProjectTrolleybus/ProjectTrolleybus/FormTrolleyBCollection.Designer.cs @@ -52,6 +52,8 @@ LoadToolStripMenuItem = new ToolStripMenuItem(); saveFileDialog = new SaveFileDialog(); openFileDialog = new OpenFileDialog(); + buttonSortByColor = new Button(); + buttonSortByType = new Button(); groupBoxTools.SuspendLayout(); panelCompanyTools.SuspendLayout(); panelStorage.SuspendLayout(); @@ -68,13 +70,15 @@ groupBoxTools.Dock = DockStyle.Right; groupBoxTools.Location = new Point(875, 24); groupBoxTools.Name = "groupBoxTools"; - groupBoxTools.Size = new Size(201, 636); + groupBoxTools.Size = new Size(201, 678); groupBoxTools.TabIndex = 0; groupBoxTools.TabStop = false; groupBoxTools.Text = "Инструменты"; // // panelCompanyTools // + panelCompanyTools.Controls.Add(buttonSortByColor); + panelCompanyTools.Controls.Add(buttonSortByType); panelCompanyTools.Controls.Add(buttonAddTrolleyB); panelCompanyTools.Controls.Add(maskedTextBoxPosition); panelCompanyTools.Controls.Add(buttonRefresh); @@ -82,15 +86,15 @@ panelCompanyTools.Controls.Add(buttonGoToCheck); panelCompanyTools.Dock = DockStyle.Bottom; panelCompanyTools.Enabled = false; - panelCompanyTools.Location = new Point(3, 355); + panelCompanyTools.Location = new Point(3, 361); panelCompanyTools.Name = "panelCompanyTools"; - panelCompanyTools.Size = new Size(195, 278); + panelCompanyTools.Size = new Size(195, 314); panelCompanyTools.TabIndex = 8; // // buttonAddTrolleyB // buttonAddTrolleyB.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonAddTrolleyB.Location = new Point(3, 12); + buttonAddTrolleyB.Location = new Point(3, 3); buttonAddTrolleyB.Name = "buttonAddTrolleyB"; buttonAddTrolleyB.Size = new Size(189, 41); buttonAddTrolleyB.TabIndex = 1; @@ -101,7 +105,7 @@ // maskedTextBoxPosition // maskedTextBoxPosition.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - maskedTextBoxPosition.Location = new Point(3, 106); + maskedTextBoxPosition.Location = new Point(3, 50); maskedTextBoxPosition.Mask = "00"; maskedTextBoxPosition.Name = "maskedTextBoxPosition"; maskedTextBoxPosition.Size = new Size(189, 23); @@ -111,7 +115,7 @@ // buttonRefresh // buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonRefresh.Location = new Point(3, 229); + buttonRefresh.Location = new Point(3, 176); buttonRefresh.Name = "buttonRefresh"; buttonRefresh.Size = new Size(189, 41); buttonRefresh.TabIndex = 6; @@ -122,7 +126,7 @@ // buttonRemoveTrolleyB // buttonRemoveTrolleyB.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonRemoveTrolleyB.Location = new Point(3, 135); + buttonRemoveTrolleyB.Location = new Point(3, 82); buttonRemoveTrolleyB.Name = "buttonRemoveTrolleyB"; buttonRemoveTrolleyB.Size = new Size(189, 41); buttonRemoveTrolleyB.TabIndex = 4; @@ -133,7 +137,7 @@ // buttonGoToCheck // buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonGoToCheck.Location = new Point(3, 182); + buttonGoToCheck.Location = new Point(3, 129); buttonGoToCheck.Name = "buttonGoToCheck"; buttonGoToCheck.Size = new Size(189, 41); buttonGoToCheck.TabIndex = 5; @@ -250,7 +254,7 @@ pictureBox.Dock = DockStyle.Fill; pictureBox.Location = new Point(0, 24); pictureBox.Name = "pictureBox"; - pictureBox.Size = new Size(875, 636); + pictureBox.Size = new Size(875, 678); pictureBox.TabIndex = 1; pictureBox.TabStop = false; // @@ -295,11 +299,33 @@ openFileDialog.FileName = "openFileDialog1"; openFileDialog.Filter = "txt file | *.txt"; // + // buttonSortByColor + // + buttonSortByColor.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + buttonSortByColor.Location = new Point(3, 270); + buttonSortByColor.Name = "buttonSortByColor"; + buttonSortByColor.Size = new Size(189, 41); + buttonSortByColor.TabIndex = 8; + buttonSortByColor.Text = "Сортировка по цвету"; + buttonSortByColor.UseVisualStyleBackColor = true; + buttonSortByColor.Click += ButtonSortByColor_Click; + // + // buttonSortByType + // + buttonSortByType.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + buttonSortByType.Location = new Point(3, 223); + buttonSortByType.Name = "buttonSortByType"; + buttonSortByType.Size = new Size(189, 41); + buttonSortByType.TabIndex = 7; + buttonSortByType.Text = "Сортировка по типу"; + buttonSortByType.UseVisualStyleBackColor = true; + buttonSortByType.Click += ButtonSortByType_Click; + // // FormTrolleyBCollection // AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(1076, 660); + ClientSize = new Size(1076, 702); Controls.Add(pictureBox); Controls.Add(groupBoxTools); Controls.Add(menuStrip); @@ -344,5 +370,7 @@ private ToolStripMenuItem LoadToolStripMenuItem; private SaveFileDialog saveFileDialog; private OpenFileDialog openFileDialog; + private Button buttonSortByColor; + private Button buttonSortByType; } } \ No newline at end of file diff --git a/ProjectTrolleybus/ProjectTrolleybus/FormTrolleyBCollection.cs b/ProjectTrolleybus/ProjectTrolleybus/FormTrolleyBCollection.cs index 09f0bf9..0183c10 100644 --- a/ProjectTrolleybus/ProjectTrolleybus/FormTrolleyBCollection.cs +++ b/ProjectTrolleybus/ProjectTrolleybus/FormTrolleyBCollection.cs @@ -269,7 +269,7 @@ public partial class FormTrolleyBCollection : 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); @@ -323,4 +323,35 @@ public partial class FormTrolleyBCollection : Form } } } + + /// + /// Сортировка по типу + /// + /// + /// + private void ButtonSortByType_Click(object sender, EventArgs e) + { + CompareTrolleyBuses(new DrawningTrolleyBCompareByType()); + } + + /// + /// Сортировка по цвету + /// + /// + /// + private void ButtonSortByColor_Click(object sender, EventArgs e) + { + CompareTrolleyBuses(new DrawningTrolleyBCompareByColor()); + } + + private void CompareTrolleyBuses(IComparer comparer) + { + if (_company == null) + { + return; + } + + _company.Sort(comparer); + pictureBox.Image = _company.Show(); + } } -- 2.25.1 From adbf4e37f0c494343e7567621fae1daa270fc9a4 Mon Sep 17 00:00:00 2001 From: Geo7312 Date: Fri, 7 Jun 2024 22:42:53 +0400 Subject: [PATCH 2/2] =?UTF-8?q?=D0=9B=D0=B0=D0=B1=D0=B0=208=20(=D0=B4?= =?UTF-8?q?=D0=BE=D0=B4=D0=B5=D0=BB=D0=B0=D0=BD=D0=BD=D0=B0=D1=8F)?= 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 +- .../ProjectTrolleybus/FormTrolleyBCollection.cs | 5 +++++ 5 files changed, 16 insertions(+), 11 deletions(-) diff --git a/ProjectTrolleybus/ProjectTrolleybus/CollectionGenericObjects/ICollectionGenericObjects.cs b/ProjectTrolleybus/ProjectTrolleybus/CollectionGenericObjects/ICollectionGenericObjects.cs index c51216f..a5db1aa 100644 --- a/ProjectTrolleybus/ProjectTrolleybus/CollectionGenericObjects/ICollectionGenericObjects.cs +++ b/ProjectTrolleybus/ProjectTrolleybus/CollectionGenericObjects/ICollectionGenericObjects.cs @@ -23,14 +23,14 @@ public interface ICollectionGenericObjects /// /// /// - int Insert(T obj, IEqualityComparer? comparer = null); + int Insert(T obj, IEqualityComparer? comparer = null); /// /// Добавление объекта в коллекцию /// /// Добавляемый объект /// true - вставка прошла удачно, false - вставка не удалась - int Insert(T obj, int position, IEqualityComparer? comparer = null); + int Insert(T obj, int position, IEqualityComparer? comparer = null); /// /// Удаление объекта из коллекции с конкретной позиции diff --git a/ProjectTrolleybus/ProjectTrolleybus/CollectionGenericObjects/ListGenericObjects.cs b/ProjectTrolleybus/ProjectTrolleybus/CollectionGenericObjects/ListGenericObjects.cs index ade2479..1445077 100644 --- a/ProjectTrolleybus/ProjectTrolleybus/CollectionGenericObjects/ListGenericObjects.cs +++ b/ProjectTrolleybus/ProjectTrolleybus/CollectionGenericObjects/ListGenericObjects.cs @@ -44,10 +44,10 @@ public class ListGenericObjects : ICollectionGenericObjects } - 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(); } @@ -62,10 +62,10 @@ public class ListGenericObjects : ICollectionGenericObjects } - 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/ProjectTrolleybus/ProjectTrolleybus/CollectionGenericObjects/MassiveGenericObjects.cs b/ProjectTrolleybus/ProjectTrolleybus/CollectionGenericObjects/MassiveGenericObjects.cs index f1e9429..9f8d6e7 100644 --- a/ProjectTrolleybus/ProjectTrolleybus/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/ProjectTrolleybus/ProjectTrolleybus/CollectionGenericObjects/MassiveGenericObjects.cs @@ -62,10 +62,10 @@ public class MassiveGenericObjects : ICollectionGenericObjects } - 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(); } @@ -84,10 +84,10 @@ public class MassiveGenericObjects : ICollectionGenericObjects } - 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/ProjectTrolleybus/ProjectTrolleybus/Exceptions/CollectionAlreadyExistsException.cs b/ProjectTrolleybus/ProjectTrolleybus/Exceptions/CollectionAlreadyExistsException.cs index 05bb400..db15130 100644 --- a/ProjectTrolleybus/ProjectTrolleybus/Exceptions/CollectionAlreadyExistsException.cs +++ b/ProjectTrolleybus/ProjectTrolleybus/Exceptions/CollectionAlreadyExistsException.cs @@ -6,7 +6,7 @@ namespace ProjectTrolleybus.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/ProjectTrolleybus/ProjectTrolleybus/FormTrolleyBCollection.cs b/ProjectTrolleybus/ProjectTrolleybus/FormTrolleyBCollection.cs index 0183c10..d5e1f01 100644 --- a/ProjectTrolleybus/ProjectTrolleybus/FormTrolleyBCollection.cs +++ b/ProjectTrolleybus/ProjectTrolleybus/FormTrolleyBCollection.cs @@ -81,6 +81,11 @@ public partial class FormTrolleyBCollection : Form MessageBox.Show(ex.Message); _logger.LogError("Ошибка: {Message}", ex.Message); } + catch (CollectionAlreadyExistsException ex) + { + MessageBox.Show(ex.Message); + _logger.LogError("Ошибка: {Message}", ex.Message); + } } -- 2.25.1