From 2d339f7d204e8044f4d416dd25f3d90aca71385c Mon Sep 17 00:00:00 2001 From: Anastasia Yazykova Date: Mon, 10 Jun 2024 03:49:04 +0400 Subject: [PATCH] =?UTF-8?q?=D0=B2=D1=81=D0=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../AbstractCompany.cs | 3 +- .../DrawningBusCompareByType.cs | 36 +++++++ .../ICollectionGenericObjects.cs | 11 ++- .../ListGenericObjects.cs | 57 ++++++++--- .../MassiveGenericObjects.cs | 49 +++++++++- .../StorageCollection.cs | 95 +++++++++++-------- .../TrolleybusProject/CollectionInfo.cs | 76 +++++++++++++++ .../Drawnings/DrawiningBusEqutables.cs | 70 ++++++++++++++ .../Drawnings/DrawningBusCompareByColor.cs | 35 +++++++ .../CollectionAlreadyExistsException.cs | 14 +++ .../Exceptions/CollectionInsertException.cs | 18 ++++ .../FormBusCollection.Designer.cs | 36 ++++++- .../TrolleybusProject/FormBusCollection.cs | 57 ++++++++--- 13 files changed, 472 insertions(+), 85 deletions(-) create mode 100644 TrolleybusProject/TrolleybusProject/CollectionGenericObjects/DrawningBusCompareByType.cs create mode 100644 TrolleybusProject/TrolleybusProject/CollectionInfo.cs create mode 100644 TrolleybusProject/TrolleybusProject/Drawnings/DrawiningBusEqutables.cs create mode 100644 TrolleybusProject/TrolleybusProject/Drawnings/DrawningBusCompareByColor.cs create mode 100644 TrolleybusProject/TrolleybusProject/Exceptions/CollectionAlreadyExistsException.cs create mode 100644 TrolleybusProject/TrolleybusProject/Exceptions/CollectionInsertException.cs diff --git a/TrolleybusProject/TrolleybusProject/CollectionGenericObjects/AbstractCompany.cs b/TrolleybusProject/TrolleybusProject/CollectionGenericObjects/AbstractCompany.cs index dcfd16e..0cb18ca 100644 --- a/TrolleybusProject/TrolleybusProject/CollectionGenericObjects/AbstractCompany.cs +++ b/TrolleybusProject/TrolleybusProject/CollectionGenericObjects/AbstractCompany.cs @@ -55,7 +55,7 @@ private int GetMaxCount => _pictureWidth / _placeSizeWidth * (_pictureHeight / _ /// public static int operator +(AbstractCompany company, DrawningBus bus) { - return company._collection.Insert(bus); + return company._collection.Insert(bus,new DrawiningBusEqutables()); } /// /// Перегрузка оператора удаления для класса @@ -102,4 +102,5 @@ private int GetMaxCount => _pictureWidth / _placeSizeWidth * (_pictureHeight / _ /// Расстановка объектов /// protected abstract void SetObjectsPosition(); + public void Sort(IComparer comparer) => _collection?.CollectionSort(comparer); } diff --git a/TrolleybusProject/TrolleybusProject/CollectionGenericObjects/DrawningBusCompareByType.cs b/TrolleybusProject/TrolleybusProject/CollectionGenericObjects/DrawningBusCompareByType.cs new file mode 100644 index 0000000..963c790 --- /dev/null +++ b/TrolleybusProject/TrolleybusProject/CollectionGenericObjects/DrawningBusCompareByType.cs @@ -0,0 +1,36 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using TrolleybusProject.Drawnings; + +namespace TrolleybusProject.CollectionGenericObjects; + +public class DrawningBusCompareByType : IComparer +{ + public int Compare(DrawningBus? x, DrawningBus? y) + { + if (x == null && y == null) return 0; + + if (x == null || x.EntityBus == null) + { + return -1; + } + if (y == null || y.EntityBus == null) + { + return 1; + } + if (x.GetType().Name != y.GetType().Name) + { + return x.GetType().Name.CompareTo(y.GetType().Name); + } + var speedCompare = x.EntityBus.Speed.CompareTo(y.EntityBus.Speed); + if (speedCompare != 0) + { + return speedCompare; + } + return x.EntityBus.Weight.CompareTo(y.EntityBus.Weight); + } + +} diff --git a/TrolleybusProject/TrolleybusProject/CollectionGenericObjects/ICollectionGenericObjects.cs b/TrolleybusProject/TrolleybusProject/CollectionGenericObjects/ICollectionGenericObjects.cs index 166273f..99c9e4a 100644 --- a/TrolleybusProject/TrolleybusProject/CollectionGenericObjects/ICollectionGenericObjects.cs +++ b/TrolleybusProject/TrolleybusProject/CollectionGenericObjects/ICollectionGenericObjects.cs @@ -21,20 +21,20 @@ 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); /// /// Удаление объекта из коллекции с конкретной позиции /// /// Позиция /// true - удаление прошло удачно, false - удаление не удалось - T? Remove(int position); + T? Remove(int position); /// /// Получение объекта по позиции /// @@ -51,4 +51,9 @@ int Insert(T obj, int position); /// /// Поэлементый вывод элементов коллекции IEnumerable GetItems(); + /// + /// Сортировка коллекции + /// + /// Сравнитель объектов + void CollectionSort(IComparer comparer); } diff --git a/TrolleybusProject/TrolleybusProject/CollectionGenericObjects/ListGenericObjects.cs b/TrolleybusProject/TrolleybusProject/CollectionGenericObjects/ListGenericObjects.cs index a72d856..b9a1bba 100644 --- a/TrolleybusProject/TrolleybusProject/CollectionGenericObjects/ListGenericObjects.cs +++ b/TrolleybusProject/TrolleybusProject/CollectionGenericObjects/ListGenericObjects.cs @@ -1,8 +1,10 @@ using System; +using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; +using TrolleybusProject.Drawnings; using TrolleybusProject.Exceptions; namespace TrolleybusProject.CollectionGenericObjects; @@ -48,27 +50,48 @@ public class ListGenericObjects : ICollectionGenericObjects return _collection[position]; } - public int Insert(T obj) + public int Insert(T obj, IEqualityComparer? comparer = null) { - if (Count + 1 > _maxCount) + if (Count == _maxCount) throw new CollectionOverflowException(Count); + if (comparer != null) + { + for (int i = 0; i < Count; i++) + { + if (comparer.Equals(_collection[i], obj)) + { + throw new CollectionInsertException(obj); + } + } + } + + _collection.Add(obj); + return Count; + } + + public int Insert(T obj, int position, IEqualityComparer? comparer = null) + { + if (Count == _maxCount) { throw new CollectionOverflowException(Count); } - _collection.Add(obj); - return 1; - } - public int Insert(T obj, int position) - { - if (position < 0 || position > Count) + if (position >= Count || position < 0) + { + throw new PositionOutOfCollectionException(position); + } + + if (comparer != null) + { + for (int i = 0; i < Count; i++) { - throw new PositionOutOfCollectionException(position); + if (comparer.Equals(_collection[i], obj)) + { + throw new CollectionInsertException(obj); + } } - if (Count + 1 > _maxCount) - { - throw new CollectionOverflowException(Count); - } - _collection.Insert(position, obj); - return 1; + } + + _collection.Insert(position, obj); + return position; } public T? Remove(int position) { @@ -89,6 +112,10 @@ public class ListGenericObjects : ICollectionGenericObjects } } + public void CollectionSort(IComparer comparer) + { + _collection.Sort(comparer); + } } diff --git a/TrolleybusProject/TrolleybusProject/CollectionGenericObjects/MassiveGenericObjects.cs b/TrolleybusProject/TrolleybusProject/CollectionGenericObjects/MassiveGenericObjects.cs index b37471f..f2ab9f9 100644 --- a/TrolleybusProject/TrolleybusProject/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/TrolleybusProject/TrolleybusProject/CollectionGenericObjects/MassiveGenericObjects.cs @@ -3,8 +3,10 @@ using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; +using TrolleybusProject.Drawnings; using TrolleybusProject.Exceptions; + namespace TrolleybusProject.CollectionGenericObjects; internal class MassiveGenericObjects : ICollectionGenericObjects @@ -51,13 +53,26 @@ internal class MassiveGenericObjects : ICollectionGenericObjects public T? Get(int position) { - if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position); - + if (position < 0 || position >= Count) + { + throw new PositionOutOfCollectionException(position); + } + return _collection[position]; } - public int Insert(T obj) + public int Insert(T obj, IEqualityComparer? comparer = null) { + if (comparer != null) + { + for (int i = 0; i < Count; i++) + { + if (comparer.Equals(_collection[i], obj)) + { + throw new CollectionInsertException(obj); + } + } + } for (int i = 0; i < Count; i++) { if (_collection[i] == null) @@ -66,12 +81,27 @@ internal class MassiveGenericObjects : ICollectionGenericObjects return i; } } - throw new CollectionOverflowException(Count); } - public int Insert(T obj, int position) + public int Insert(T obj, int position, IEqualityComparer? comparer = null) { + if (position < 0 || position >= Count) + { + throw new PositionOutOfCollectionException(position); + } + + if (comparer != null) + { + for (int i = 0; i < Count; i++) + { + if (comparer.Equals(_collection[i], obj)) + { + throw new CollectionInsertException(obj); + } + } + } + if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position); if (_collection[position] == null) { @@ -117,4 +147,13 @@ internal class MassiveGenericObjects : ICollectionGenericObjects yield return _collection[i]; } } + + public void CollectionSort(IComparer comparer) + { + List value = new List(_collection); + value.Sort(comparer); + value.CopyTo(_collection, 0); + } + + } diff --git a/TrolleybusProject/TrolleybusProject/CollectionGenericObjects/StorageCollection.cs b/TrolleybusProject/TrolleybusProject/CollectionGenericObjects/StorageCollection.cs index 27fb31c..cc1a24b 100644 --- a/TrolleybusProject/TrolleybusProject/CollectionGenericObjects/StorageCollection.cs +++ b/TrolleybusProject/TrolleybusProject/CollectionGenericObjects/StorageCollection.cs @@ -1,4 +1,5 @@ -using System; +using ProjectTrolleybus.Exceptions; +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -15,12 +16,12 @@ public class StorageCollection /// /// Словарь (хранилище) с коллекциями /// - readonly Dictionary> _storages; + readonly Dictionary> _storages; /// /// Возвращение списка названий коллекций /// - public List Keys => _storages.Keys.ToList(); + public List Keys => _storages.Keys.ToList(); /// /// Ключевое слово, с которого должен начинаться файл @@ -42,7 +43,7 @@ public class StorageCollection /// public StorageCollection() { - _storages = new Dictionary>(); + _storages = new Dictionary>(); } /// /// Добавление коллекции в хранилище @@ -51,29 +52,36 @@ public class StorageCollection /// тип коллекции public void AddCollection(string name, CollectionType collectionType) { - if (_storages.ContainsKey(name) && name == "") - { + CollectionInfo collectionInfo = new(name, collectionType, string.Empty); + if (name == null || _storages.ContainsKey(collectionInfo)) return; + switch (collectionType) + { + case CollectionType.None: + return; + case CollectionType.Massive: + _storages[collectionInfo] = new MassiveGenericObjects(); + return; + case CollectionType.List: + _storages[collectionInfo] = new ListGenericObjects(); + return; + default: + break; } - if (collectionType == CollectionType.Massive) - { - _storages[name] = new MassiveGenericObjects(); - } - else - { - _storages[name] = new ListGenericObjects(); - } } - /// /// Удаление коллекции /// /// Название коллекции public void DelCollection(string name) { - _storages.Remove(name); -} + CollectionInfo collectionInfo = new CollectionInfo(name, CollectionType.None, string.Empty); + if (_storages.ContainsKey(collectionInfo)) + { + _storages.Remove(collectionInfo); + } + } /// /// Доступ к коллекции /// @@ -83,11 +91,12 @@ public class StorageCollection { get { - if (name == "") + CollectionInfo collectionInfo = new CollectionInfo(name, CollectionType.None, string.Empty); + if (_storages.ContainsKey(collectionInfo)) { - return null; + return _storages[collectionInfo]; } - return _storages[name]; + return null; } } @@ -102,10 +111,13 @@ public class StorageCollection { File.Delete(filename); } + using (StreamWriter writer = new(filename)) + + { writer.Write(_collectionKey); - foreach (KeyValuePair> value in _storages) + foreach (KeyValuePair> value in _storages) { writer.Write(Environment.NewLine); // не сохраняем пустые коллекции @@ -141,42 +153,42 @@ public class StorageCollection { throw new FileNotFoundException("Файл не существует!"); } - using (StreamReader reader = new(filename)) + + using (StreamReader sr = new(filename)) { - string line = reader.ReadLine(); + string? line = sr.ReadLine(); + if (line == null || line.Length == 0) { throw new ArgumentException("В файле нет данных"); } - if (!line.Equals(_collectionKey)) + + if (line != _collectionKey) { - throw new InvalidDataException("В файле неверные данные"); + throw new InvalidDataException("В файле неверные данные"); } + _storages.Clear(); - while ((line = reader.ReadLine()) != null) + + while ((line = sr.ReadLine()) != null) { - string[] record = line.Split(_separatorForKeyValue, - StringSplitOptions.RemoveEmptyEntries); - if (record.Length != 4) + string[] record = line.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); + + if (record.Length != 3) { continue; } - CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]); - ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType); - if (collection == null) - { - throw new InvalidCastException("Не удалось определить тип коллекции: " + record[1]); - } - collection.MaxCount = Convert.ToInt32(record[2]); - string[] set = record[3].Split(_separatorItems, - StringSplitOptions.RemoveEmptyEntries); + CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(record[0]) ?? throw new ArgumentNullException("Не удалось определить тип коллекции: " + record[0]); + ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionInfo.CollectionType) ?? throw new ArgumentNullException("Не удалось создать коллекцию"); + collection.MaxCount = Convert.ToInt32(record[1]); + string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); foreach (string elem in set) { - if (elem?.CreateDrawningBus() is T boat) + if (elem?.CreateDrawningBus() is T bus) { try { - if (collection.Insert(boat) < 0) + if (collection.Insert(bus) < 0) { throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]); @@ -189,10 +201,9 @@ public class StorageCollection } } - _storages.Add(record[0], collection); + _storages.Add(collectionInfo, collection); } } - } /// diff --git a/TrolleybusProject/TrolleybusProject/CollectionInfo.cs b/TrolleybusProject/TrolleybusProject/CollectionInfo.cs new file mode 100644 index 0000000..ece6558 --- /dev/null +++ b/TrolleybusProject/TrolleybusProject/CollectionInfo.cs @@ -0,0 +1,76 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using TrolleybusProject.CollectionGenericObjects; + +namespace TrolleybusProject; +/// +/// Класс, хранящиий информацию по коллекции +/// +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/TrolleybusProject/TrolleybusProject/Drawnings/DrawiningBusEqutables.cs b/TrolleybusProject/TrolleybusProject/Drawnings/DrawiningBusEqutables.cs new file mode 100644 index 0000000..ff0c4cc --- /dev/null +++ b/TrolleybusProject/TrolleybusProject/Drawnings/DrawiningBusEqutables.cs @@ -0,0 +1,70 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using TrolleybusProject.Entities; + +namespace TrolleybusProject.Drawnings; + +internal class DrawiningBusEqutables: IEqualityComparer +{ + public bool Equals(DrawningBus? x, DrawningBus? y) + { + if (x == null || x.EntityBus == null) + { + return false; + } + if (y == null || y.EntityBus == null) + { + return false; + } + if (x.GetType().Name != y.GetType().Name) + { + return false; + } + if (x.EntityBus.Speed != y.EntityBus.Speed) + { + return false; + } + if (x.EntityBus.Weight != y.EntityBus.Weight) + { + return false; + } + if (x.EntityBus.BodyColor != y.EntityBus.BodyColor) + { + return false; + } + if (x is DrawningTrolleybus && y is DrawningTrolleybus) + { + if (((EntityTrolleybus)x.EntityBus).AdditionalColor != + ((EntityTrolleybus)y.EntityBus).AdditionalColor) + { + return false; + } + if (((EntityTrolleybus)x.EntityBus).Roga != + ((EntityTrolleybus)y.EntityBus).Roga) + { + return false; + } + if (((EntityTrolleybus)x.EntityBus).Otsek != + ((EntityTrolleybus)y.EntityBus).Otsek) + { + return false; + } + + if (((EntityTrolleybus)x.EntityBus).Doors != + ((EntityTrolleybus)y.EntityBus).Doors) + { + return false; + } + } + return true; + } + public int GetHashCode([DisallowNull] DrawningBus obj) + { + return obj.GetHashCode(); + } + +} diff --git a/TrolleybusProject/TrolleybusProject/Drawnings/DrawningBusCompareByColor.cs b/TrolleybusProject/TrolleybusProject/Drawnings/DrawningBusCompareByColor.cs new file mode 100644 index 0000000..81716a7 --- /dev/null +++ b/TrolleybusProject/TrolleybusProject/Drawnings/DrawningBusCompareByColor.cs @@ -0,0 +1,35 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace TrolleybusProject.Drawnings; + +public class DrawningBusCompareByColor: IComparer +{ + public int Compare(DrawningBus? x, DrawningBus? y) + { + if (x == null || x.EntityBus == null) + { + return 1; + } + + if (y == null || y.EntityBus == null) + { + return -1; + } + var bodycolorCompare = x.EntityBus.BodyColor.Name.CompareTo(y.EntityBus.BodyColor.Name); + if (bodycolorCompare != 0) + { + return bodycolorCompare; + } + var speedCompare = x.EntityBus.Speed.CompareTo(y.EntityBus.Speed); + if (speedCompare != 0) + { + return speedCompare; + } + return x.EntityBus.Weight.CompareTo(y.EntityBus.Weight); + } + +} diff --git a/TrolleybusProject/TrolleybusProject/Exceptions/CollectionAlreadyExistsException.cs b/TrolleybusProject/TrolleybusProject/Exceptions/CollectionAlreadyExistsException.cs new file mode 100644 index 0000000..7e8b4a0 --- /dev/null +++ b/TrolleybusProject/TrolleybusProject/Exceptions/CollectionAlreadyExistsException.cs @@ -0,0 +1,14 @@ +using System.Runtime.Serialization; +using TrolleybusProject; + +namespace ProjectTrolleybus.Exceptions; +public class CollectionAlreadyExistsException : Exception +{ + public CollectionAlreadyExistsException() : base() { } + public CollectionAlreadyExistsException(CollectionInfo collectioninfo) : base($"Коллекция {collectioninfo} уже существует!") { } + public CollectionAlreadyExistsException(string name, Exception exception) : + base($"Коллекция {name} уже существует!", exception) + { } + protected CollectionAlreadyExistsException(SerializationInfo info, StreamingContext + contex) : base(info, contex) { } +} \ No newline at end of file diff --git a/TrolleybusProject/TrolleybusProject/Exceptions/CollectionInsertException.cs b/TrolleybusProject/TrolleybusProject/Exceptions/CollectionInsertException.cs new file mode 100644 index 0000000..d97edcb --- /dev/null +++ b/TrolleybusProject/TrolleybusProject/Exceptions/CollectionInsertException.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +public class CollectionInsertException : Exception +{ + public CollectionInsertException(object obj) : base($"Объект {obj} повторяется") { } + public CollectionInsertException() : base() { } + public CollectionInsertException(string message) : base(message) { } + public CollectionInsertException(string message, Exception exception) : + base(message, exception) + { } + protected CollectionInsertException(SerializationInfo info, StreamingContext + contex) : base(info, contex) { } +} \ No newline at end of file diff --git a/TrolleybusProject/TrolleybusProject/FormBusCollection.Designer.cs b/TrolleybusProject/TrolleybusProject/FormBusCollection.Designer.cs index aa68b52..bd66250 100644 --- a/TrolleybusProject/TrolleybusProject/FormBusCollection.Designer.cs +++ b/TrolleybusProject/TrolleybusProject/FormBusCollection.Designer.cs @@ -55,6 +55,8 @@ LoadToolStripMenuItem = new ToolStripMenuItem(); saveFileDialog = new SaveFileDialog(); openFileDialog = new OpenFileDialog(); + buttonByType = new Button(); + ByColor = new Button(); groupBoxTools.SuspendLayout(); panelCompanyTools.SuspendLayout(); panelStorage.SuspendLayout(); @@ -71,7 +73,7 @@ groupBoxTools.Dock = DockStyle.Right; groupBoxTools.Location = new Point(904, 33); groupBoxTools.Name = "groupBoxTools"; - groupBoxTools.Size = new Size(300, 623); + groupBoxTools.Size = new Size(300, 702); groupBoxTools.TabIndex = 0; groupBoxTools.TabStop = false; groupBoxTools.Text = "Инструменты"; @@ -88,7 +90,9 @@ // // panelCompanyTools // + panelCompanyTools.Controls.Add(buttonByType); panelCompanyTools.Controls.Add(buttonRefresh); + panelCompanyTools.Controls.Add(ByColor); panelCompanyTools.Controls.Add(buttonGoToCheck); panelCompanyTools.Controls.Add(buttonAddBus); panelCompanyTools.Controls.Add(buttonDelTrolleybus); @@ -96,7 +100,7 @@ panelCompanyTools.Enabled = false; panelCompanyTools.Location = new Point(0, 397); panelCompanyTools.Name = "panelCompanyTools"; - panelCompanyTools.Size = new Size(294, 259); + panelCompanyTools.Size = new Size(294, 305); panelCompanyTools.TabIndex = 9; // // buttonRefresh @@ -250,7 +254,7 @@ pictureBox.Dock = DockStyle.Fill; pictureBox.Location = new Point(0, 33); pictureBox.Name = "pictureBox"; - pictureBox.Size = new Size(904, 623); + pictureBox.Size = new Size(904, 702); pictureBox.TabIndex = 1; pictureBox.TabStop = false; // @@ -314,11 +318,33 @@ // openFileDialog.Filter = "txt file | *.txt"; // + // buttonByType + // + buttonByType.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + buttonByType.Location = new Point(6, 259); + buttonByType.Name = "buttonByType"; + buttonByType.Size = new Size(268, 34); + buttonByType.TabIndex = 8; + buttonByType.Text = "Сравнить по типу"; + buttonByType.UseVisualStyleBackColor = true; + buttonByType.Click += button1_Click; + // + // ByColor + // + ByColor.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + ByColor.Location = new Point(23, 215); + ByColor.Name = "ByColor"; + ByColor.Size = new Size(247, 38); + ByColor.TabIndex = 7; + ByColor.Text = "Сравнить по цвету"; + ByColor.UseVisualStyleBackColor = true; + ByColor.Click += ByColor_Click; + // // FormBusCollection // AutoScaleDimensions = new SizeF(10F, 25F); AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(1204, 656); + ClientSize = new Size(1204, 735); Controls.Add(pictureBox); Controls.Add(groupBoxTools); Controls.Add(menuStrip); @@ -366,5 +392,7 @@ private ToolStripMenuItem файлToolStripMenuItem; private ToolStripMenuItem save_ToolStripMenuItem; private ToolStripMenuItem load_ToolStripMenuItem; + private Button buttonByType; + private Button ByColor; } } \ No newline at end of file diff --git a/TrolleybusProject/TrolleybusProject/FormBusCollection.cs b/TrolleybusProject/TrolleybusProject/FormBusCollection.cs index aae2f7e..218ce27 100644 --- a/TrolleybusProject/TrolleybusProject/FormBusCollection.cs +++ b/TrolleybusProject/TrolleybusProject/FormBusCollection.cs @@ -45,24 +45,26 @@ public partial class FormBusCollection : Form } private void SetBus(DrawningBus bus) { + if (_company == null || bus == null) + { + return; + } try { - if (_company == null || bus == null) - { - return; - } - if (_company + bus != -1) - { - MessageBox.Show("Объект добавлен"); - pictureBox.Image = _company.Show(); - _logger.LogInformation("Добавлен объект: {0}", bus.GetDataForSave()); - } - + int addingObject = (_company + bus); + MessageBox.Show("Объект добавлен"); + _logger.LogInformation($"Добавлен объект {bus.GetDataForSave()}"); + pictureBox.Image = _company.Show(); } catch (CollectionOverflowException ex) { - MessageBox.Show(ex.Message); - _logger.LogError($"Ошибка: {ex.Message}"); + MessageBox.Show("Не удалось добавить объект"); + _logger.LogWarning($"Не удалось добавить объект: {ex.Message}"); + } + catch (CollectionInsertException) + { + MessageBox.Show("Такой объект уже существует"); + _logger.LogError("Ошибка:обьект повторяется {0}", bus); } } @@ -156,7 +158,7 @@ public partial class FormBusCollection : Form private void buttonCollectionAdd_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(textBoxCollectionName.Text) || - (!radioButtonList.Checked && !radioButtonMassive.Checked)) + (!radioButtonList.Checked && !radioButtonMassive.Checked)) { MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); @@ -184,7 +186,7 @@ public partial class FormBusCollection : 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); @@ -281,6 +283,31 @@ public partial class FormBusCollection : Form } + private void button1_Click(object sender, EventArgs e) + { + CompareBus(new DrawningBusCompareByType()); + } + + private void ByColor_Click(object sender, EventArgs e) + { + CompareBus(new DrawningBusCompareByColor()); + } + + /// + /// Сортировка по сравнителю + /// + /// Сравнитель объектов + private void CompareBus(IComparer comparer) + { + if (_company == null) + { + return; + } + _company.Sort(comparer); + pictureBox.Image = _company.Show(); + } + + }