diff --git a/lab_0/CollectionGenericObject/AbstractCompany.cs b/lab_0/CollectionGenericObject/AbstractCompany.cs index e91d543..f166bdc 100644 --- a/lab_0/CollectionGenericObject/AbstractCompany.cs +++ b/lab_0/CollectionGenericObject/AbstractCompany.cs @@ -1,5 +1,6 @@ using ProjectBus.Drawnings; using ProjectBus.Exceptions; +using System.Threading.Tasks; namespace ProjectBus.CollectionGenericObject; /// @@ -59,7 +60,8 @@ public abstract class AbstractCompany /// public static int operator +(AbstractCompany company, DrawningSimpleBus simplebus) { - return company._collection.Insert(simplebus); + return company._collection?.Insert(simplebus, new DrawningSimpleBusEquitables()) ?? + throw new DrawningEquitablesException(); } /// @@ -73,6 +75,8 @@ public abstract class AbstractCompany return company._collection?.Remove(position); } + public void Sort(IComparer comparer) =>_collection?.CollectionSort(comparer); + /// /// Получение случайного объекта из коллекции /// diff --git a/lab_0/CollectionGenericObject/ColletctionInfo.cs b/lab_0/CollectionGenericObject/ColletctionInfo.cs new file mode 100644 index 0000000..37d356e --- /dev/null +++ b/lab_0/CollectionGenericObject/ColletctionInfo.cs @@ -0,0 +1,88 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectBus.CollectionGenericObject; + +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 bool IsEmpty() + { + if (string.IsNullOrEmpty(Name) && CollectionType != CollectionType.None) return true; + return false; + } + + public override int GetHashCode() + { + return Name.GetHashCode(); + } +} diff --git a/lab_0/CollectionGenericObject/ICollectionGenericObjects.cs b/lab_0/CollectionGenericObject/ICollectionGenericObjects.cs index b4f7d1e..15fedf7 100644 --- a/lab_0/CollectionGenericObject/ICollectionGenericObjects.cs +++ b/lab_0/CollectionGenericObject/ICollectionGenericObjects.cs @@ -28,7 +28,7 @@ namespace ProjectBus.CollectionGenericObject; /// /// Добавляемый объект /// true - вставка прошла удачно, false - вставка не удалась - int Insert(T obj); + int Insert(T obj, IEqualityComparer? comparer = null); /// /// Добавление объекта в коллекцию на конкретную позицию @@ -36,7 +36,7 @@ namespace ProjectBus.CollectionGenericObject; /// Добавляемый объект /// Позиция /// true - вставка прошла удачно, false - вставка не удалась - int Insert(T obj, int position); + int Insert(T obj, int position, IEqualityComparer? comparer = null); /// /// Удаление объекта из коллекции с конкретной позиции @@ -62,7 +62,13 @@ namespace ProjectBus.CollectionGenericObject; /// /// Поэлементый вывод элементов коллекции IEnumerable GetItems(); -} + + /// + /// Сортировка коллекции + /// + /// Сравнитель объектов + void CollectionSort(IComparer comparer); + } diff --git a/lab_0/CollectionGenericObject/ListGenericObjects.cs b/lab_0/CollectionGenericObject/ListGenericObjects.cs index 890d317..1069fa0 100644 --- a/lab_0/CollectionGenericObject/ListGenericObjects.cs +++ b/lab_0/CollectionGenericObject/ListGenericObjects.cs @@ -52,20 +52,48 @@ public class ListGenericObjects : ICollectionGenericObjects } - public int Insert(T obj) + public int Insert(T obj, IEqualityComparer? comparer = null) { 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) + public int Insert(T obj, int position, IEqualityComparer? comparer = null) { if (Count == _maxCount) throw new CollectionOverflowException(Count); if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position); + + if (comparer != null) + { + for (int i = 0; i < Count; i++) + { + if (comparer.Equals(_collection[i], obj)) + { + throw new CollectionInsertException(obj); + } + } + } + _collection.Insert(position, obj); return position; } + public void CollectionSort(IComparer comparer) + { + _collection.Sort(comparer); + } + public T Remove(int position) { diff --git a/lab_0/CollectionGenericObject/MassiveGenericObjects.cs b/lab_0/CollectionGenericObject/MassiveGenericObjects.cs index ba7e618..9fe17a0 100644 --- a/lab_0/CollectionGenericObject/MassiveGenericObjects.cs +++ b/lab_0/CollectionGenericObject/MassiveGenericObjects.cs @@ -63,8 +63,20 @@ namespace ProjectBus.CollectionGenericObject; } - 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++) { @@ -78,14 +90,22 @@ namespace ProjectBus.CollectionGenericObject; 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 (_collection[position] != null) { bool pushed = false; @@ -118,7 +138,6 @@ namespace ProjectBus.CollectionGenericObject; } } - // вставка _collection[position] = obj; return position; } @@ -141,4 +160,9 @@ namespace ProjectBus.CollectionGenericObject; yield return _collection[i]; } } + + public void CollectionSort(IComparer comparer) + { + Array.Sort(_collection, comparer); + } } \ No newline at end of file diff --git a/lab_0/CollectionGenericObject/StorageCollection.cs b/lab_0/CollectionGenericObject/StorageCollection.cs index 343f3eb..74c16a0 100644 --- a/lab_0/CollectionGenericObject/StorageCollection.cs +++ b/lab_0/CollectionGenericObject/StorageCollection.cs @@ -16,90 +16,56 @@ namespace ProjectBus.CollectionGenericObject; public class StorageCollection where T : DrawningSimpleBus -{/// - /// Словарь (хранилище) с коллекциями - /// - readonly Dictionary> _storages; +{ - /// - /// Возвращение списка названий коллекций - /// - public List Keys => _storages.Keys.ToList(); + readonly Dictionary> _storages; - /// - /// Ключевое слово, с которого должен начинаться файл - /// + + public List Keys => _storages.Keys.ToList(); + + public StorageCollection() + { + _storages = new Dictionary>(); + } + public void AddCollection(CollectionInfo collectionInfo) + { + if (_storages.ContainsKey(collectionInfo)) throw new CollectionAlreadyExistsException(collectionInfo); + if (collectionInfo.CollectionType == CollectionType.None) + throw new CollectionTypeException("Пустой тип коллекции"); + if (collectionInfo.CollectionType == CollectionType.Massive) + _storages[collectionInfo] = new MassiveGenericObjects(); + else if (collectionInfo.CollectionType == CollectionType.List) + _storages[collectionInfo] = new ListGenericObjects(); + } + public void DelCollection(CollectionInfo collectionInfo) + { + if (_storages.ContainsKey(collectionInfo)) + _storages.Remove(collectionInfo); + } + + public ICollectionGenericObjects? this[CollectionInfo collectionInfo] + { + get + { + if (_storages.ContainsKey(collectionInfo)) + return _storages[collectionInfo]; + return null; + } + } private readonly string _collectionKey = "CollectionsStorage"; - /// /// Разделитель для записи ключа и значения элемента словаря /// private readonly string _separatorForKeyValue = "|"; - /// /// Разделитель для записей коллекции данных в файл /// private readonly string _separatorItems = ";"; - - /// - /// Конструктор - /// - public StorageCollection() - { - _storages = new Dictionary>(); - } - - /// - /// Добавление коллекции в хранилище - /// - /// Название коллекции - /// тип коллекции - public void AddCollection(string name, CollectionType collectionType) - { - if (_storages.ContainsKey(name)) return; - if (collectionType == CollectionType.None) return; - else if (collectionType == CollectionType.Massive) - _storages[name] = new MassiveGenericObjects(); - else if (collectionType == CollectionType.List) - _storages[name] = new ListGenericObjects(); - - } - - /// - /// Удаление коллекции - /// - /// Название коллекции - public void DelCollection(string name) - { - if (_storages.ContainsKey(name)) - _storages.Remove(name); - } - - /// - /// Доступ к коллекции - /// - /// Название коллекции - /// - public ICollectionGenericObjects? this[string name] - { - get - { - if (_storages.ContainsKey(name)) - return _storages[name]; - return null; - } - } - - /// - /// Сохранение информации по автомобилям в хранилище в файл - /// - /// Путь и имя файла - /// true - сохранение прошло успешно, false - ошибка при сохранении данных - public void SaveData(string filename) + public bool SaveData(string filename) { if (_storages.Count == 0) { - throw new InvalidDataException("В хранилище отсутствуют коллекции для сохранения"); + throw new EmptyFileExeption(); } if (File.Exists(filename)) @@ -110,7 +76,7 @@ public class StorageCollection using (StreamWriter writer = new StreamWriter(filename)) { writer.Write(_collectionKey); - foreach (KeyValuePair> value in _storages) + foreach (KeyValuePair> value in _storages) { StringBuilder sb = new(); sb.Append(Environment.NewLine); @@ -139,7 +105,10 @@ public class StorageCollection } writer.Write(sb); } + } + return true; + } /// @@ -151,64 +120,61 @@ public class StorageCollection { if (!File.Exists(filename)) { - throw new FileNotFoundException($"{filename} не существует"); + throw new FileNotFoundException(filename); } using (StreamReader fs = File.OpenText(filename)) { string str = fs.ReadLine(); - if (str == null || str.Length == 0) + if (string.IsNullOrEmpty(str)) { - throw new FileFormatException("Файл не подходит"); + throw new EmptyFileExeption(filename); } + if (!str.StartsWith(_collectionKey)) { - throw new IOException("В файле неверные данные"); + throw new FileFormatException(filename); } + _storages.Clear(); string strs = ""; while ((strs = fs.ReadLine()) != null) { string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); - if (record.Length != 4) + if (record.Length != 3) { continue; } - CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]); - ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType); - 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 CollectionInfoException("Не удалось определить информацию коллекции:" + record[0]); + + ICollectionGenericObjects? collection = + StorageCollection.CreateCollection(collectionInfo.CollectionType) ?? + throw new CollectionTypeException("Не удалось определить тип коллекции:" + record[1]); + collection.MaxCount = Convert.ToInt32(record[1]); + + string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); foreach (string elem in set) { - if (elem?.CreateDrawningSimpleBus() is T simpleBus) + if (elem?.CreateDrawningSimpleBus() is T ship) { try { - if (collection.Insert(simpleBus) == -1) - { - throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]); - } + collection.Insert(ship); } - catch (CollectionOverflowException ex) + catch (Exception ex) { - throw new DataException("Коллекция переполнена", ex); + throw new FileFormatException(filename, ex); } } } - _storages.Add(record[0], collection); + + _storages.Add(collectionInfo, collection); } } } - - /// - /// Создание коллекции по типу - /// - /// - /// private static ICollectionGenericObjects? CreateCollection(CollectionType collectionType) { return collectionType switch @@ -219,4 +185,3 @@ public class StorageCollection }; } } - diff --git a/lab_0/CollectionGenericObject/StorageCollectionEqutables.cs b/lab_0/CollectionGenericObject/StorageCollectionEqutables.cs new file mode 100644 index 0000000..7dcfb92 --- /dev/null +++ b/lab_0/CollectionGenericObject/StorageCollectionEqutables.cs @@ -0,0 +1,12 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectBus.CollectionGenericObject +{ + internal class StorageCollectionEqutables + { + } +} diff --git a/lab_0/Drawnings/DrawningBusCompareByColor.cs b/lab_0/Drawnings/DrawningBusCompareByColor.cs new file mode 100644 index 0000000..0ab6952 --- /dev/null +++ b/lab_0/Drawnings/DrawningBusCompareByColor.cs @@ -0,0 +1,34 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectBus.Drawnings; + +public class DrawningBusCompareByColor : IComparer +{ + public int Compare(DrawningSimpleBus? x, DrawningSimpleBus? y) + { + if (x == null || x.EntitySimpleBus == null) + { + return 1; + } + + if (y == null || y.EntitySimpleBus == null) + { + return -1; + } + var bodycolorCompare = x.EntitySimpleBus.BodyColor.Name.CompareTo(y.EntitySimpleBus.BodyColor.Name); + if (bodycolorCompare != 0) + { + return bodycolorCompare; + } + var speedCompare = x.EntitySimpleBus.Speed.CompareTo(y.EntitySimpleBus.Speed); + if (speedCompare != 0) + { + return speedCompare; + } + return x.EntitySimpleBus.Weight.CompareTo(y.EntitySimpleBus.Weight); + } +} diff --git a/lab_0/Drawnings/DrawningBusCompareByType.cs b/lab_0/Drawnings/DrawningBusCompareByType.cs new file mode 100644 index 0000000..6050d19 --- /dev/null +++ b/lab_0/Drawnings/DrawningBusCompareByType.cs @@ -0,0 +1,38 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectBus.Drawnings; + +public class DrawningBusCompareByType : IComparer +{ + public int Compare(DrawningSimpleBus? x, DrawningSimpleBus? y) + { + if (x == null && y == null) return 0; + if (x == null || x.EntitySimpleBus == null) + { + return 1; + } + + if (y == null || y.EntitySimpleBus == null) + { + return -1; + } + + if (x.GetType().Name != y.GetType().Name) + { + return x.GetType().Name.CompareTo(y.GetType().Name); + } + + var speedCompare = x.EntitySimpleBus.Speed.CompareTo(y.EntitySimpleBus.Speed); + if (speedCompare != 0) + { + return speedCompare; + } + + return x.EntitySimpleBus.Weight.CompareTo(y.EntitySimpleBus.Weight); + } +} + diff --git a/lab_0/Drawnings/DrawningEquitablesException.cs b/lab_0/Drawnings/DrawningEquitablesException.cs new file mode 100644 index 0000000..a4b7d27 --- /dev/null +++ b/lab_0/Drawnings/DrawningEquitablesException.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectBus.Drawnings; + +public class DrawningEquitablesException : Exception +{ + public DrawningEquitablesException() : base("Объекты прорисовки одинаковые") { } + public DrawningEquitablesException(string message) : base(message) { } + public DrawningEquitablesException(string message, Exception exception) : base(message, exception) + { } + protected DrawningEquitablesException(SerializationInfo info, StreamingContext contex) : base(info, contex) { } +} diff --git a/lab_0/Drawnings/DrawningSimpleBusEquitables.cs b/lab_0/Drawnings/DrawningSimpleBusEquitables.cs new file mode 100644 index 0000000..7090d0e --- /dev/null +++ b/lab_0/Drawnings/DrawningSimpleBusEquitables.cs @@ -0,0 +1,70 @@ +using ProjectBus.Entities; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectBus.Drawnings; + +public class DrawningSimpleBusEquitables : IEqualityComparer +{ + public bool Equals(DrawningSimpleBus? x, DrawningSimpleBus? y) + { + if (x == null || x.EntitySimpleBus == null) + { + return false; + } + + if (y == null || y.EntitySimpleBus == null) + { + return false; + } + + if (x.GetType().Name != y.GetType().Name) + { + return false; + } + + if (x.EntitySimpleBus.Speed != y.EntitySimpleBus.Speed) + { + return false; + } + + if (x.EntitySimpleBus.Weight != y.EntitySimpleBus.Weight) + { + return false; + } + + if (x.EntitySimpleBus.BodyColor != y.EntitySimpleBus.BodyColor) + { + return false; + } + + if (x is DrawningBus && y is DrawningBus) + { + EntityBus entityX = (EntityBus)x.EntitySimpleBus; + EntityBus entityY = (EntityBus)y.EntitySimpleBus; + if (entityX.AdditionalCompartment != entityY.AdditionalCompartment) + { + return false; + } + if (entityX.Accordion != entityY.Accordion) + { + return false; + } + if (entityX.AdditionalColor != entityY.AdditionalColor) + { + return false; + } + } + + return true; + } + + public int GetHashCode([DisallowNull] DrawningSimpleBus obj) + { + return obj.GetHashCode(); + } +} diff --git a/lab_0/Exceptions/CollectionAlreadyExistsException.cs b/lab_0/Exceptions/CollectionAlreadyExistsException.cs index 367c50d..91b53af 100644 --- a/lab_0/Exceptions/CollectionAlreadyExistsException.cs +++ b/lab_0/Exceptions/CollectionAlreadyExistsException.cs @@ -1,4 +1,5 @@ -using System; +using ProjectBus.CollectionGenericObject; +using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; @@ -7,11 +8,14 @@ using System.Threading.Tasks; namespace ProjectBus.Exceptions; +[Serializable] public class CollectionAlreadyExistsException : Exception { public CollectionAlreadyExistsException() : base() { } - public CollectionAlreadyExistsException(string name) : base($"Коллекция {name} уже существует!") { } - public CollectionAlreadyExistsException(string name, Exception exception) :base($"Коллекция {name} уже существует!", exception) + public CollectionAlreadyExistsException(CollectionInfo collectionInfo) : base($"Коллекция {collectionInfo} уже существует!") { } + public CollectionAlreadyExistsException(string name, Exception exception) : + base($"Коллекция {name} уже существует!", exception) { } - protected CollectionAlreadyExistsException(SerializationInfo info, StreamingContext contex) : base(info, contex) { } -} + protected CollectionAlreadyExistsException(SerializationInfo info, StreamingContext + contex) : base(info, contex) { } +} \ No newline at end of file diff --git a/lab_0/Exceptions/CollectionInfoException.cs b/lab_0/Exceptions/CollectionInfoException.cs new file mode 100644 index 0000000..8ac8880 --- /dev/null +++ b/lab_0/Exceptions/CollectionInfoException.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectBus.Exceptions; + +public class CollectionInfoException : Exception +{ + public CollectionInfoException() : base() { } + public CollectionInfoException(string message) : base(message) { } + public CollectionInfoException(string message, Exception exception) : + base(message, exception) + { } + protected CollectionInfoException(SerializationInfo info, StreamingContext + contex) : base(info, contex) { } +} \ No newline at end of file diff --git a/lab_0/Exceptions/CollectionInsertException.cs b/lab_0/Exceptions/CollectionInsertException.cs index b90d4f0..09209a5 100644 --- a/lab_0/Exceptions/CollectionInsertException.cs +++ b/lab_0/Exceptions/CollectionInsertException.cs @@ -9,10 +9,10 @@ namespace ProjectBus.Exceptions; 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) + public CollectionInsertException(string message, Exception exception) : base(message, exception) { } protected CollectionInsertException(SerializationInfo info, StreamingContext contex) : base(info, contex) { } - } diff --git a/lab_0/FormSimpleBusCollection.Designer.cs b/lab_0/FormSimpleBusCollection.Designer.cs index f36372a..936a409 100644 --- a/lab_0/FormSimpleBusCollection.Designer.cs +++ b/lab_0/FormSimpleBusCollection.Designer.cs @@ -30,6 +30,8 @@ { groupBoxTools = new GroupBox(); panelCompanyTools = new Panel(); + buttonSortByColor = new Button(); + buttonSortByType = new Button(); buttonAddSimpleBus = new Button(); maskedTextBox = new MaskedTextBox(); buttonRefresh = new Button(); @@ -64,7 +66,7 @@ groupBoxTools.Controls.Add(panelCompanyTools); groupBoxTools.Controls.Add(panelStorage); groupBoxTools.Dock = DockStyle.Right; - groupBoxTools.Location = new Point(1018, 40); + groupBoxTools.Location = new Point(1091, 40); groupBoxTools.Name = "groupBoxTools"; groupBoxTools.Size = new Size(356, 1018); groupBoxTools.TabIndex = 0; @@ -73,6 +75,8 @@ // // panelCompanyTools // + panelCompanyTools.Controls.Add(buttonSortByColor); + panelCompanyTools.Controls.Add(buttonSortByType); panelCompanyTools.Controls.Add(buttonAddSimpleBus); panelCompanyTools.Controls.Add(maskedTextBox); panelCompanyTools.Controls.Add(buttonRefresh); @@ -85,9 +89,31 @@ panelCompanyTools.Size = new Size(350, 445); panelCompanyTools.TabIndex = 8; // + // buttonSortByColor + // + buttonSortByColor.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + buttonSortByColor.Location = new Point(3, 366); + buttonSortByColor.Name = "buttonSortByColor"; + buttonSortByColor.Size = new Size(328, 49); + buttonSortByColor.TabIndex = 9; + buttonSortByColor.Text = "Сортировка по цвету"; + buttonSortByColor.UseVisualStyleBackColor = true; + buttonSortByColor.Click += buttonSortByColor_Click; + // + // buttonSortByType + // + buttonSortByType.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + buttonSortByType.Location = new Point(6, 297); + buttonSortByType.Name = "buttonSortByType"; + buttonSortByType.Size = new Size(328, 49); + buttonSortByType.TabIndex = 8; + buttonSortByType.Text = "Сортировка по типу"; + buttonSortByType.UseVisualStyleBackColor = true; + buttonSortByType.Click += buttonSortByType_Click; + // // buttonAddSimpleBus // - buttonAddSimpleBus.Location = new Point(9, 48); + buttonAddSimpleBus.Location = new Point(12, 3); buttonAddSimpleBus.Name = "buttonAddSimpleBus"; buttonAddSimpleBus.Size = new Size(318, 59); buttonAddSimpleBus.TabIndex = 1; @@ -97,7 +123,7 @@ // // maskedTextBox // - maskedTextBox.Location = new Point(13, 135); + maskedTextBox.Location = new Point(18, 68); maskedTextBox.Mask = "00"; maskedTextBox.Name = "maskedTextBox"; maskedTextBox.Size = new Size(306, 39); @@ -107,7 +133,7 @@ // buttonRefresh // buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonRefresh.Location = new Point(6, 365); + buttonRefresh.Location = new Point(6, 229); buttonRefresh.Name = "buttonRefresh"; buttonRefresh.Size = new Size(328, 49); buttonRefresh.TabIndex = 7; @@ -118,7 +144,7 @@ // buttonDelBus // buttonDelBus.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonDelBus.Location = new Point(6, 200); + buttonDelBus.Location = new Point(6, 113); buttonDelBus.Name = "buttonDelBus"; buttonDelBus.Size = new Size(321, 46); buttonDelBus.TabIndex = 5; @@ -129,7 +155,7 @@ // buttonGoToCheck // buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonGoToCheck.Location = new Point(6, 277); + buttonGoToCheck.Location = new Point(3, 165); buttonGoToCheck.Name = "buttonGoToCheck"; buttonGoToCheck.Size = new Size(328, 58); buttonGoToCheck.TabIndex = 6; @@ -247,7 +273,7 @@ pictureBox.Dock = DockStyle.Fill; pictureBox.Location = new Point(0, 40); pictureBox.Name = "pictureBox"; - pictureBox.Size = new Size(1018, 1018); + pictureBox.Size = new Size(1091, 1018); pictureBox.TabIndex = 0; pictureBox.TabStop = false; // @@ -257,7 +283,7 @@ menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem }); menuStrip.Location = new Point(0, 0); menuStrip.Name = "menuStrip"; - menuStrip.Size = new Size(1374, 40); + menuStrip.Size = new Size(1447, 40); menuStrip.TabIndex = 1; menuStrip.Text = "menuStrip"; // @@ -296,7 +322,7 @@ // AutoScaleDimensions = new SizeF(13F, 32F); AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(1374, 1058); + ClientSize = new Size(1447, 1058); 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/lab_0/FormSimpleBusCollection.cs b/lab_0/FormSimpleBusCollection.cs index d3fd8a5..d8118c9 100644 --- a/lab_0/FormSimpleBusCollection.cs +++ b/lab_0/FormSimpleBusCollection.cs @@ -86,40 +86,7 @@ public partial class FormSimpleBusCollection : Form /// Создание объекта класса-перемещения /// /// Тип создаваемого объекта - private void CreateObject(string type) - { - if (_company == null) - { - return; - } - Random random = new(); - DrawningSimpleBus drawningSimpleBus; - switch (type) - { - case nameof(DrawningSimpleBus): - drawningSimpleBus = new DrawningSimpleBus(random.Next(100, 300), random.Next(1000, 3000), GetColor(random)); - break; - case nameof(DrawningBus): - // вызов диалогового окна для выбора цвета - drawningSimpleBus = new DrawningBus(random.Next(100, 300), random.Next(1000, 3000), - GetColor(random), - GetColor(random), - Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2))); - break; - default: - return; - } - if (_company + drawningSimpleBus != -1) - { - MessageBox.Show("Объект добавлен"); - pictureBox.Image = _company.Show(); - } - else - { - _ = MessageBox.Show(drawningSimpleBus.ToString()); - } - } private Color GetColor(Random random) { @@ -240,7 +207,7 @@ public partial class FormSimpleBusCollection : Form try { - _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); + _storageCollection.AddCollection(new CollectionInfo(textBoxCollectionName.Text, collectionType, "ХЗ")); _logger.LogInformation("Добавление коллекции"); RerfreshListBoxItems(); } @@ -249,8 +216,6 @@ public partial class FormSimpleBusCollection : Form MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); _logger.LogError($"Ошибка: {ex.Message}", ex.Message); } - - } /// @@ -272,7 +237,8 @@ public partial class FormSimpleBusCollection : Form return; } - _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString()); + CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(listBoxCollection.SelectedItem.ToString()!); + _storageCollection.DelCollection(collectionInfo!); _logger.LogInformation("Коллекция удалена"); RerfreshListBoxItems(); } @@ -286,13 +252,12 @@ public partial class FormSimpleBusCollection : Form listBoxCollection.Items.Clear(); for (int i = 0; i < _storageCollection.Keys?.Count; ++i) { - string? colName = _storageCollection.Keys?[i]; - if (!string.IsNullOrEmpty(colName)) + CollectionInfo? col = _storageCollection.Keys?[i]; + if (!col!.IsEmpty()) { - listBoxCollection.Items.Add(colName); + listBoxCollection.Items.Add(col); } } - } /// @@ -308,7 +273,10 @@ public partial class FormSimpleBusCollection : Form return; } - ICollectionGenericObjects? collection = _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty]; + ICollectionGenericObjects? collection = + _storageCollection[ + CollectionInfo.GetCollectionInfo(listBoxCollection.SelectedItem.ToString()!) ?? + new CollectionInfo("", CollectionType.None, "")]; if (collection == null) { MessageBox.Show("Коллекция не проинициализирована"); @@ -381,9 +349,32 @@ public partial class FormSimpleBusCollection : Form } } } + + + private void buttonSortByType_Click(object sender, EventArgs e) + { + CompareBus(new DrawningBusCompareByType()); + } + + private void buttonSortByColor_Click(object sender, EventArgs e) + { + CompareBus(new DrawningBusCompareByColor()); + } + + private void CompareBus(IComparer comparer) + { + if (_company == null) + { + return; + } + + _company.Sort(comparer); + pictureBox.Image = _company.Show(); + } } +