From 23e695e60d1c8a2405234201224ae92019b6f360 Mon Sep 17 00:00:00 2001 From: DanilaSm08 Date: Sun, 19 May 2024 12:53:44 +0400 Subject: [PATCH] Lab8 in process --- .../AbstractCompany.cs | 15 ++- .../CarSharingCompany.cs | 2 +- .../CollectionInfo.cs | 71 ++++++++++++++ .../ICollectionGenericObjects.cs | 12 ++- .../ListGenericObjects.cs | 27 ++++-- .../MassiveGenericObjects.cs | 24 ++++- .../StorageCollection.cs | 93 ++++++++----------- .../Drawnings/DrawningTruckCompareByColor.cs | 34 +++++++ .../Drawnings/DrawningTruckCompareByType.cs | 33 +++++++ .../Drawnings/DrawningTruckEqutables.cs | 66 +++++++++++++ .../Exceptions/ObjectNotFoundException.cs | 2 +- .../Exceptions/ObjectNotUniqueException.cs | 16 ++++ .../PositionOutOfCollectionException.cs | 2 +- .../FormTruckCollection.Designer.cs | 63 ++++++++++--- .../ProjectCleaningCar/FormTruckCollection.cs | 42 +++++++-- 15 files changed, 409 insertions(+), 93 deletions(-) create mode 100644 ProjectCleaningCar/ProjectCleaningCar/CollectionGenericObjects/CollectionInfo.cs create mode 100644 ProjectCleaningCar/ProjectCleaningCar/Drawnings/DrawningTruckCompareByColor.cs create mode 100644 ProjectCleaningCar/ProjectCleaningCar/Drawnings/DrawningTruckCompareByType.cs create mode 100644 ProjectCleaningCar/ProjectCleaningCar/Drawnings/DrawningTruckEqutables.cs create mode 100644 ProjectCleaningCar/ProjectCleaningCar/Exceptions/ObjectNotUniqueException.cs diff --git a/ProjectCleaningCar/ProjectCleaningCar/CollectionGenericObjects/AbstractCompany.cs b/ProjectCleaningCar/ProjectCleaningCar/CollectionGenericObjects/AbstractCompany.cs index 94a76e7..af596db 100644 --- a/ProjectCleaningCar/ProjectCleaningCar/CollectionGenericObjects/AbstractCompany.cs +++ b/ProjectCleaningCar/ProjectCleaningCar/CollectionGenericObjects/AbstractCompany.cs @@ -1,5 +1,5 @@ using ProjectCleaningCar.Drawnings; -using ProjectSportCar.Exceptions; +using ProjectCleaningCar.Exceptions; namespace ProjectCleaningCar.CollectionGenericObjects; /// @@ -48,11 +48,15 @@ public abstract class AbstractCompany /// Перегрузка оператора сложения для класса /// /// Компания - /// Добавляемый объект + /// Добавляемый объект /// public static int operator +(AbstractCompany company, DrawningTruck truck) { - return company._collection?.Insert(truck) ?? -1; + if (company._collection == null) + { + return -1; + } + return company._collection.Insert(truck, new DrawiningTruckEqutables()); } /// @@ -95,6 +99,11 @@ public abstract class AbstractCompany } return bitmap; } + /// + /// Сортировка + /// + /// Сравнитель объектов + public void Sort(IComparer comparer) => _collection?.CollectionSort(comparer); /// /// Вывод заднего фона /// diff --git a/ProjectCleaningCar/ProjectCleaningCar/CollectionGenericObjects/CarSharingCompany.cs b/ProjectCleaningCar/ProjectCleaningCar/CollectionGenericObjects/CarSharingCompany.cs index 91c2448..c950fa3 100644 --- a/ProjectCleaningCar/ProjectCleaningCar/CollectionGenericObjects/CarSharingCompany.cs +++ b/ProjectCleaningCar/ProjectCleaningCar/CollectionGenericObjects/CarSharingCompany.cs @@ -1,5 +1,5 @@ using ProjectCleaningCar.Drawnings; -using ProjectSportCar.Exceptions; +using ProjectCleaningCar.Exceptions; namespace ProjectCleaningCar.CollectionGenericObjects; /// diff --git a/ProjectCleaningCar/ProjectCleaningCar/CollectionGenericObjects/CollectionInfo.cs b/ProjectCleaningCar/ProjectCleaningCar/CollectionGenericObjects/CollectionInfo.cs new file mode 100644 index 0000000..2adf310 --- /dev/null +++ b/ProjectCleaningCar/ProjectCleaningCar/CollectionGenericObjects/CollectionInfo.cs @@ -0,0 +1,71 @@ +namespace ProjectCleaningCar.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/ProjectCleaningCar/ProjectCleaningCar/CollectionGenericObjects/ICollectionGenericObjects.cs b/ProjectCleaningCar/ProjectCleaningCar/CollectionGenericObjects/ICollectionGenericObjects.cs index 50a775a..2830c85 100644 --- a/ProjectCleaningCar/ProjectCleaningCar/CollectionGenericObjects/ICollectionGenericObjects.cs +++ b/ProjectCleaningCar/ProjectCleaningCar/CollectionGenericObjects/ICollectionGenericObjects.cs @@ -28,16 +28,17 @@ where T : class /// Добавление объекта в коллекцию /// /// Добавляемый объект + /// Cравнение двух объектов /// true - вставка прошла удачно, false - вставка не удалась - int Insert(T obj); - + int Insert(T obj, IEqualityComparer? comparer = null); /// /// Добавление объекта в коллекцию на конкретную позицию /// /// Добавляемый объект /// Позиция + /// Cравнение двух объектов /// true - вставка прошла удачно, false - вставка не удалась - int Insert(T obj, int position); + int Insert(T obj, int position, IEqualityComparer? comparer = null); /// /// Удаление объекта из коллекции с конкретной позиции @@ -62,4 +63,9 @@ where T : class /// /// Поэлементый вывод элементов коллекции IEnumerable GetItems(); + /// + /// Сортировка коллекции + /// + /// Сравнитель объектов + void CollectionSort(IComparer comparer); } diff --git a/ProjectCleaningCar/ProjectCleaningCar/CollectionGenericObjects/ListGenericObjects.cs b/ProjectCleaningCar/ProjectCleaningCar/CollectionGenericObjects/ListGenericObjects.cs index 13ee70f..ba8298b 100644 --- a/ProjectCleaningCar/ProjectCleaningCar/CollectionGenericObjects/ListGenericObjects.cs +++ b/ProjectCleaningCar/ProjectCleaningCar/CollectionGenericObjects/ListGenericObjects.cs @@ -1,10 +1,4 @@ using ProjectCleaningCar.Exceptions; -using ProjectSportCar.Exceptions; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace ProjectCleaningCar.CollectionGenericObjects; /// @@ -53,24 +47,34 @@ public class ListGenericObjects : ICollectionGenericObjects } - public int Insert(T obj) + public int Insert(T obj, IEqualityComparer? comparer) { + if (_collection.Contains(obj, comparer)) + { + throw new ObjectNotUniqueException(); + } + if (Count == _maxCount) { throw new CollectionOverflowException(_collection.Count); } _collection.Add(obj); return Count; } - public int Insert(T obj, int position) + public int Insert(T obj, int position, IEqualityComparer? comparer) { + if (_collection.Contains(obj, comparer)) + { + throw new ObjectNotUniqueException(position); + } + if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(); if (Count == _maxCount) throw new CollectionOverflowException(); _collection.Insert(position, obj); return position; - } + public T Remove(int position) { if (position < 0 || position >= _collection.Count) throw new PositionOutOfCollectionException(position); @@ -87,4 +91,9 @@ public class ListGenericObjects : ICollectionGenericObjects yield return _collection[i]; } } + + public void CollectionSort(IComparer comparer) + { + _collection.Sort(comparer); + } } diff --git a/ProjectCleaningCar/ProjectCleaningCar/CollectionGenericObjects/MassiveGenericObjects.cs b/ProjectCleaningCar/ProjectCleaningCar/CollectionGenericObjects/MassiveGenericObjects.cs index 7e43941..f736c8b 100644 --- a/ProjectCleaningCar/ProjectCleaningCar/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/ProjectCleaningCar/ProjectCleaningCar/CollectionGenericObjects/MassiveGenericObjects.cs @@ -1,5 +1,5 @@ -using ProjectCleaningCar.Exceptions; -using ProjectSportCar.Exceptions; +using ProjectCleaningCar.Drawnings; +using ProjectCleaningCar.Exceptions; namespace ProjectCleaningCar.CollectionGenericObjects; /// @@ -62,12 +62,12 @@ internal class MassiveGenericObjects : ICollectionGenericObjects return _collection[position]; } - public int Insert(T obj) + public int Insert(T obj, IEqualityComparer? comparer = null) { - return Insert(obj, 0); + return Insert(obj, 0, comparer); } - public int Insert(T obj, int position) + public int Insert(T obj, int position, IEqualityComparer? comparer = null) { if (!(position >= 0 && position < Count)) throw new PositionOutOfCollectionException(position); @@ -77,6 +77,15 @@ internal class MassiveGenericObjects : ICollectionGenericObjects return position; } + if (comparer != null) + { + foreach (T? item in _collection) + { + if ((comparer as IEqualityComparer).Equals(obj as DrawningTruck, item as DrawningTruck)) + throw new ObjectNotUniqueException(position); + } + } + for (int i = position + 1; i < Count; i++) { if (_collection[i] == null) @@ -115,5 +124,10 @@ internal class MassiveGenericObjects : ICollectionGenericObjects yield return _collection[i]; } } + + public void CollectionSort(IComparer comparer) + { + Array.Sort(_collection, comparer); + } } diff --git a/ProjectCleaningCar/ProjectCleaningCar/CollectionGenericObjects/StorageCollection.cs b/ProjectCleaningCar/ProjectCleaningCar/CollectionGenericObjects/StorageCollection.cs index 94b4403..167b300 100644 --- a/ProjectCleaningCar/ProjectCleaningCar/CollectionGenericObjects/StorageCollection.cs +++ b/ProjectCleaningCar/ProjectCleaningCar/CollectionGenericObjects/StorageCollection.cs @@ -13,11 +13,11 @@ public class StorageCollection /// /// Словарь (хранилище) с коллекциями /// - readonly Dictionary> _storages; + readonly Dictionary> _storages; /// /// Возвращение списка названий коллекций /// - public List Keys => _storages.Keys.ToList(); + public List Keys => _storages.Keys.ToList(); /// /// Ключевое слово, с которого должен начинаться файл @@ -37,7 +37,7 @@ public class StorageCollection /// public StorageCollection() { - _storages = new Dictionary>(); + _storages = new Dictionary>(); } /// /// Добавление коллекции в хранилище @@ -46,30 +46,20 @@ public class StorageCollection /// тип коллекции public void AddCollection(string name, CollectionType collectionType) { - if (string.IsNullOrEmpty(name)) - { - throw new ArgumentException("Название коллекции не может быть пустым или null", nameof(name)); - } - - if (_storages.ContainsKey(name)) - { - throw new ArgumentException($"Коллекция с именем {name} уже существует", nameof(name)); - } - - ICollectionGenericObjects collection; + CollectionInfo collectionInfo = new CollectionInfo(name, collectionType, string.Empty); + if (name == null || _storages.ContainsKey(collectionInfo)) { return; } switch (collectionType) - { - case CollectionType.List: - collection = new ListGenericObjects(); - break; - case CollectionType.Massive: - collection = new MassiveGenericObjects(); - break; - default: - throw new ArgumentException($"Неизвестный тип коллекции: {collectionType}", nameof(collectionType)); - } - _storages.Add(name, collection); + { + case CollectionType.None: + return; + case CollectionType.Massive: + _storages.Add(collectionInfo, new MassiveGenericObjects { }); + return; + case CollectionType.List: + _storages.Add(collectionInfo, new ListGenericObjects { }); + return; + } } /// @@ -78,10 +68,9 @@ public class StorageCollection /// Название коллекции public void DelCollection(string name) { - if (_storages.ContainsKey(name)) - { - _storages.Remove(name); - } + CollectionInfo collectionInfo = new CollectionInfo(name, CollectionType.None, string.Empty); + if (name == null || !_storages.ContainsKey(collectionInfo)) { return; } + _storages.Remove(collectionInfo); } /// /// Доступ к коллекции @@ -92,11 +81,9 @@ public class StorageCollection { get { - if (_storages.TryGetValue(name, out ICollectionGenericObjects? collection)) - { - return collection; - } - return null; + CollectionInfo collectionInfo = new CollectionInfo(name, CollectionType.None, string.Empty); + if (collectionInfo == null || !_storages.ContainsKey(collectionInfo)) { return null; } + return _storages[collectionInfo]; } } /// @@ -107,7 +94,7 @@ public class StorageCollection { if (_storages.Count == 0) { - throw new Exception("В хранилище отсутствуют коллекции для сохранения"); + throw new ArgumentException("В хранилище отсутствуют коллекции для сохранения"); } if (File.Exists(filename)) @@ -120,17 +107,16 @@ public class StorageCollection using (StreamWriter sw = new StreamWriter(filename)) { sw.WriteLine(_collectionKey.ToString()); - foreach (KeyValuePair> kvpair in _storages) + foreach (KeyValuePair> kvpair in _storages) { // не сохраняем пустые коллекции if (kvpair.Value.Count == 0) continue; sb.Append(kvpair.Key); sb.Append(_separatorForKeyValue); - sb.Append(kvpair.Value.GetCollectionType); - sb.Append(_separatorForKeyValue); sb.Append(kvpair.Value.MaxCount); sb.Append(_separatorForKeyValue); + foreach (T? item in kvpair.Value.GetItems()) { string data = item?.GetDataForSave() ?? string.Empty; @@ -152,43 +138,44 @@ public class StorageCollection { if (!File.Exists(filename)) { - throw new Exception("Файл не существует"); + throw new FileNotFoundException("Файл не существует"); } using (StreamReader sr = new StreamReader(filename)) { string? str; str = sr.ReadLine(); - if (str != _collectionKey.ToString()) - throw new Exception("Не удалось преобразовать данные"); + if (str != _collectionKey.ToString()) throw new FormatException("В файле неверные данные"); _storages.Clear(); while ((str = sr.ReadLine()) != null) { string[] record = str.Split(_separatorForKeyValue); - 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) ?? + throw new Exception("Не удалось определить тип коллекции:" + record[1]); + if (collection == null) { - throw new Exception("В файле нет данных"); + throw new InvalidOperationException("Не удалось определить тип коллекции:" + record[1]); } - collection.MaxCount = Convert.ToInt32(record[2]); + collection.MaxCount = Convert.ToInt32(record[1]); - string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); + string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); foreach (string elem in set) { - if (elem?.CreateDrawningTruck() is T truck) + if (elem?.CreateDrawningTruck() is T plane) { try { - if (collection.Insert(truck) == -1) - { - throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]); - } + if (collection.Insert(plane) == -1) throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]); } catch (CollectionOverflowException ex) { @@ -196,7 +183,7 @@ public class StorageCollection } } } - _storages.Add(record[0], collection); + _storages.Add(collectionInfo, collection); } } } diff --git a/ProjectCleaningCar/ProjectCleaningCar/Drawnings/DrawningTruckCompareByColor.cs b/ProjectCleaningCar/ProjectCleaningCar/Drawnings/DrawningTruckCompareByColor.cs new file mode 100644 index 0000000..2eb2ea9 --- /dev/null +++ b/ProjectCleaningCar/ProjectCleaningCar/Drawnings/DrawningTruckCompareByColor.cs @@ -0,0 +1,34 @@ +namespace ProjectCleaningCar.Drawnings; + +/// +/// Сравнение по цвету, скорости, весу +/// +public class DrawningTruckCompareByColor : IComparer +{ + public int Compare(DrawningTruck? x, DrawningTruck? y) + { + if (x == null || x.EntityTruck == null) + { + return 1; + } + + if (y == null || y.EntityTruck == null) + { + return -1; + } + + var bodycolorCompare = y.EntityTruck.BodyColor.Name.CompareTo(x.EntityTruck.BodyColor.Name); + if (bodycolorCompare != 0) + { + return bodycolorCompare; + } + + var speedCompare = y.EntityTruck.Speed.CompareTo(x.EntityTruck.Speed); + if (speedCompare != 0) + { + return speedCompare; + } + + return y.EntityTruck.Weight.CompareTo(x.EntityTruck.Weight); + } +} diff --git a/ProjectCleaningCar/ProjectCleaningCar/Drawnings/DrawningTruckCompareByType.cs b/ProjectCleaningCar/ProjectCleaningCar/Drawnings/DrawningTruckCompareByType.cs new file mode 100644 index 0000000..171d400 --- /dev/null +++ b/ProjectCleaningCar/ProjectCleaningCar/Drawnings/DrawningTruckCompareByType.cs @@ -0,0 +1,33 @@ +namespace ProjectCleaningCar.Drawnings; + +/// +/// Сравнение по типу, скорости, весу +/// +public class DrawningTruckCompareByType : IComparer +{ + public int Compare(DrawningTruck? x, DrawningTruck? y) + { + if (x == null || x.EntityTruck == null) + { + return 1; + } + + if (y == null || y.EntityTruck == null) + { + return -1; + } + + if (x.GetType().Name != y.GetType().Name) + { + return y.GetType().Name.CompareTo(x.GetType().Name); + } + + var speedCompare = y.EntityTruck.Speed.CompareTo(x.EntityTruck.Speed); + if (speedCompare != 0) + { + return speedCompare; + } + + return y.EntityTruck.Weight.CompareTo(x.EntityTruck.Weight); + } +} diff --git a/ProjectCleaningCar/ProjectCleaningCar/Drawnings/DrawningTruckEqutables.cs b/ProjectCleaningCar/ProjectCleaningCar/Drawnings/DrawningTruckEqutables.cs new file mode 100644 index 0000000..58b0a09 --- /dev/null +++ b/ProjectCleaningCar/ProjectCleaningCar/Drawnings/DrawningTruckEqutables.cs @@ -0,0 +1,66 @@ +using ProjectCleaningCar.Entites; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectCleaningCar.Drawnings; +/// +/// Реализация сравнения двух объектов класса-прорисовки +/// +public class DrawiningTruckEqutables : IEqualityComparer +{ + public bool Equals(DrawningTruck? x, DrawningTruck? y) + { + if (x == null || x.EntityTruck == null) + { + return false; + } + if (y == null || y.EntityTruck == null) + { + return false; + } + if (x.GetType().Name != y.GetType().Name) + { + return false; + } + if (x.EntityTruck.Speed != y.EntityTruck.Speed) + { + return false; + } + if (x.EntityTruck.Weight != y.EntityTruck.Weight) + { + return false; + } + if (x.EntityTruck.BodyColor != y.EntityTruck.BodyColor) + { + return false; + } + if (x is DrawningCleaningCar && y is DrawningCleaningCar) + { + EntityCleaningCar _x = (EntityCleaningCar)x.EntityTruck; + EntityCleaningCar _y = (EntityCleaningCar)x.EntityTruck; + + if (_x.AdditionalColor != _y.AdditionalColor) + { + return false; + } + if (_x.WaterTank != _y.WaterTank) + { + return false; + } + if (_x.SweepingBrush != _y.SweepingBrush) + { + return false; + } + } + return true; + } + public int GetHashCode([DisallowNull] DrawningTruck obj) + { + return obj.GetHashCode(); + } +} + diff --git a/ProjectCleaningCar/ProjectCleaningCar/Exceptions/ObjectNotFoundException.cs b/ProjectCleaningCar/ProjectCleaningCar/Exceptions/ObjectNotFoundException.cs index 0f07b6f..e636374 100644 --- a/ProjectCleaningCar/ProjectCleaningCar/Exceptions/ObjectNotFoundException.cs +++ b/ProjectCleaningCar/ProjectCleaningCar/Exceptions/ObjectNotFoundException.cs @@ -1,5 +1,5 @@ using System.Runtime.Serialization; -namespace ProjectSportCar.Exceptions; +namespace ProjectCleaningCar.Exceptions; /// /// Класс, описывающий ошибку, что по указанной позиции нет элемента diff --git a/ProjectCleaningCar/ProjectCleaningCar/Exceptions/ObjectNotUniqueException.cs b/ProjectCleaningCar/ProjectCleaningCar/Exceptions/ObjectNotUniqueException.cs new file mode 100644 index 0000000..2cb49ac --- /dev/null +++ b/ProjectCleaningCar/ProjectCleaningCar/Exceptions/ObjectNotUniqueException.cs @@ -0,0 +1,16 @@ +using System.Runtime.Serialization; + +namespace ProjectCleaningCar.Exceptions; + +/// +/// Класс, описывающий ошибку наличия такого же объекта в коллекции +/// +[Serializable] +internal class ObjectNotUniqueException : ApplicationException +{ + public ObjectNotUniqueException(int count) : base("В коллекции содержится равный элемент: " + count) { } + public ObjectNotUniqueException() : base() { } + public ObjectNotUniqueException(string message) : base(message) { } + public ObjectNotUniqueException(string message, Exception exception) : base(message, exception) { } + protected ObjectNotUniqueException(SerializationInfo info, StreamingContext contex) : base(info, contex) { } +} \ No newline at end of file diff --git a/ProjectCleaningCar/ProjectCleaningCar/Exceptions/PositionOutOfCollectionException.cs b/ProjectCleaningCar/ProjectCleaningCar/Exceptions/PositionOutOfCollectionException.cs index e679562..9ccd3ae 100644 --- a/ProjectCleaningCar/ProjectCleaningCar/Exceptions/PositionOutOfCollectionException.cs +++ b/ProjectCleaningCar/ProjectCleaningCar/Exceptions/PositionOutOfCollectionException.cs @@ -1,5 +1,5 @@ using System.Runtime.Serialization; -namespace ProjectSportCar.Exceptions; +namespace ProjectCleaningCar.Exceptions; /// /// Класс, описывающий ошибку выхода за границы коллекции diff --git a/ProjectCleaningCar/ProjectCleaningCar/FormTruckCollection.Designer.cs b/ProjectCleaningCar/ProjectCleaningCar/FormTruckCollection.Designer.cs index 6dfcde1..90faf26 100644 --- a/ProjectCleaningCar/ProjectCleaningCar/FormTruckCollection.Designer.cs +++ b/ProjectCleaningCar/ProjectCleaningCar/FormTruckCollection.Designer.cs @@ -53,6 +53,9 @@ namespace ProjectCleaningCar LoadToolStripMenuItem = new ToolStripMenuItem(); saveFileDialog = new SaveFileDialog(); openFileDialog = new OpenFileDialog(); + button1 = new Button(); + buttonSortByColor = new Button(); + buttonSortByType = new Button(); groupBoxTools.SuspendLayout(); panelCompanyTools.SuspendLayout(); panelStorage.SuspendLayout(); @@ -69,13 +72,15 @@ namespace ProjectCleaningCar groupBoxTools.Dock = DockStyle.Right; groupBoxTools.Location = new Point(927, 28); groupBoxTools.Name = "groupBoxTools"; - groupBoxTools.Size = new Size(250, 641); + groupBoxTools.Size = new Size(250, 652); groupBoxTools.TabIndex = 0; groupBoxTools.TabStop = false; groupBoxTools.Text = "Инструменты"; // // panelCompanyTools // + panelCompanyTools.Controls.Add(buttonSortByType); + panelCompanyTools.Controls.Add(buttonSortByColor); panelCompanyTools.Controls.Add(buttonAdd); panelCompanyTools.Controls.Add(maskedTextBoxPosition); panelCompanyTools.Controls.Add(buttonRefresh); @@ -83,15 +88,15 @@ namespace ProjectCleaningCar panelCompanyTools.Controls.Add(buttonGoToCheck); panelCompanyTools.Dock = DockStyle.Bottom; panelCompanyTools.Enabled = false; - panelCompanyTools.Location = new Point(3, 393); + panelCompanyTools.Location = new Point(3, 394); panelCompanyTools.Name = "panelCompanyTools"; - panelCompanyTools.Size = new Size(244, 245); + panelCompanyTools.Size = new Size(244, 255); panelCompanyTools.TabIndex = 8; // // buttonAdd // buttonAdd.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonAdd.Location = new Point(13, 3); + buttonAdd.Location = new Point(15, 2); buttonAdd.Name = "buttonAdd"; buttonAdd.Size = new Size(220, 33); buttonAdd.TabIndex = 1; @@ -101,7 +106,7 @@ namespace ProjectCleaningCar // // maskedTextBoxPosition // - maskedTextBoxPosition.Location = new Point(15, 98); + maskedTextBoxPosition.Location = new Point(15, 42); maskedTextBoxPosition.Mask = "00"; maskedTextBoxPosition.Name = "maskedTextBoxPosition"; maskedTextBoxPosition.Size = new Size(220, 27); @@ -111,9 +116,9 @@ namespace ProjectCleaningCar // buttonRefresh // buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonRefresh.Location = new Point(15, 201); + buttonRefresh.Location = new Point(13, 149); buttonRefresh.Name = "buttonRefresh"; - buttonRefresh.Size = new Size(220, 35); + buttonRefresh.Size = new Size(220, 29); buttonRefresh.TabIndex = 6; buttonRefresh.Text = "Обновить"; buttonRefresh.UseVisualStyleBackColor = true; @@ -122,7 +127,7 @@ namespace ProjectCleaningCar // buttonRemoveTruck // buttonRemoveTruck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonRemoveTruck.Location = new Point(15, 131); + buttonRemoveTruck.Location = new Point(15, 75); buttonRemoveTruck.Name = "buttonRemoveTruck"; buttonRemoveTruck.Size = new Size(220, 31); buttonRemoveTruck.TabIndex = 4; @@ -133,7 +138,7 @@ namespace ProjectCleaningCar // buttonGoToCheck // buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonGoToCheck.Location = new Point(15, 168); + buttonGoToCheck.Location = new Point(15, 112); buttonGoToCheck.Name = "buttonGoToCheck"; buttonGoToCheck.Size = new Size(220, 31); buttonGoToCheck.TabIndex = 5; @@ -250,7 +255,7 @@ namespace ProjectCleaningCar pictureBox.Dock = DockStyle.Fill; pictureBox.Location = new Point(0, 28); pictureBox.Name = "pictureBox"; - pictureBox.Size = new Size(927, 641); + pictureBox.Size = new Size(927, 652); pictureBox.TabIndex = 1; pictureBox.TabStop = false; // @@ -295,12 +300,45 @@ namespace ProjectCleaningCar // openFileDialog.Filter = "txt file | *.txt"; // + // button1 + // + button1.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + button1.Location = new Point(728, 584); + button1.Name = "button1"; + button1.Size = new Size(0, 29); + button1.TabIndex = 7; + button1.Text = "Обновить"; + button1.UseVisualStyleBackColor = true; + // + // buttonSortByColor + // + buttonSortByColor.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + buttonSortByColor.Location = new Point(15, 217); + buttonSortByColor.Name = "buttonSortByColor"; + buttonSortByColor.Size = new Size(220, 29); + 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(15, 184); + buttonSortByType.Name = "buttonSortByType"; + buttonSortByType.Size = new Size(220, 29); + buttonSortByType.TabIndex = 9; + buttonSortByType.Text = "Сортировка по типу"; + buttonSortByType.UseVisualStyleBackColor = true; + buttonSortByType.Click += buttonSortByType_Click; + // // FormTruckCollection // AutoScaleDimensions = new SizeF(8F, 20F); AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(1177, 669); + ClientSize = new Size(1177, 680); Controls.Add(pictureBox); + Controls.Add(button1); Controls.Add(groupBoxTools); Controls.Add(menuStrip); MainMenuStrip = menuStrip; @@ -344,5 +382,8 @@ namespace ProjectCleaningCar private ToolStripMenuItem LoadToolStripMenuItem; private SaveFileDialog saveFileDialog; private OpenFileDialog openFileDialog; + private Button buttonSortByType; + private Button buttonSortByColor; + private Button button1; } } \ No newline at end of file diff --git a/ProjectCleaningCar/ProjectCleaningCar/FormTruckCollection.cs b/ProjectCleaningCar/ProjectCleaningCar/FormTruckCollection.cs index abd8ccc..df421a8 100644 --- a/ProjectCleaningCar/ProjectCleaningCar/FormTruckCollection.cs +++ b/ProjectCleaningCar/ProjectCleaningCar/FormTruckCollection.cs @@ -2,9 +2,6 @@ using ProjectCleaningCar.CollectionGenericObjects; using ProjectCleaningCar.Drawnings; using ProjectCleaningCar.Exceptions; -using ProjectSportCar.Exceptions; -using System.Numerics; -using System.Windows.Forms; namespace ProjectCleaningCar; /// @@ -227,10 +224,10 @@ public partial class FormTruckCollection : Form listBoxCollection.Items.Clear(); for (int i = 0; i < _storageCollection.Keys?.Count; ++i) { - string? colName = _storageCollection.Keys?[i]; - if (!string.IsNullOrEmpty(colName)) + string? name = _storageCollection.Keys?[i].Name; + if (!string.IsNullOrEmpty(name)) { - listBoxCollection.Items.Add(colName); + listBoxCollection.Items.Add(name); } } } @@ -307,4 +304,37 @@ public partial class FormTruckCollection : Form } } } + + /// + /// Сортировка по типу + /// + /// + /// + private void buttonSortByType_Click(object sender, EventArgs e) + { + CompareTrucks(new DrawningTruckCompareByType()); + } + /// + /// Сортировка по цвету + /// + /// + /// + private void buttonSortByColor_Click(object sender, EventArgs e) + { + CompareTrucks(new DrawningTruckCompareByColor()); + } + /// + /// Сортировка по сравнителю + /// + /// Сравнитель объектов + private void CompareTrucks(IComparer comparer) + { + if (_company == null) + { + return; + } + _company.Sort(comparer); + pictureBox.Image = _company.Show(); + } + }