diff --git a/Excavator/Excavator/CollectionGenericObjects/AbstractCompany.cs b/Excavator/Excavator/CollectionGenericObjects/AbstractCompany.cs index 201fd1b..93d8d12 100644 --- a/Excavator/Excavator/CollectionGenericObjects/AbstractCompany.cs +++ b/Excavator/Excavator/CollectionGenericObjects/AbstractCompany.cs @@ -65,7 +65,7 @@ public abstract class AbstractCompany { return -1; } - return company._collection.Insert(car); + return company._collection.Insert(car, new DrawningTrackedVehicleEqutables()); } /// /// Перегрузка оператора удаления для класса @@ -111,6 +111,11 @@ public abstract class AbstractCompany } return bitmap; } + /// + /// Сортировка + /// + /// Сравнитель объектов + public void Sort(IComparer comparer) => _collection?.CollectionSort(comparer); /// /// Вывод заднего фона diff --git a/Excavator/Excavator/CollectionGenericObjects/CollectionInfo.cs b/Excavator/Excavator/CollectionGenericObjects/CollectionInfo.cs new file mode 100644 index 0000000..1f8d098 --- /dev/null +++ b/Excavator/Excavator/CollectionGenericObjects/CollectionInfo.cs @@ -0,0 +1,77 @@ +namespace Excavator.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/Excavator/Excavator/CollectionGenericObjects/ICollectionGenericObjects.cs b/Excavator/Excavator/CollectionGenericObjects/ICollectionGenericObjects.cs index 4824bf3..000b2fc 100644 --- a/Excavator/Excavator/CollectionGenericObjects/ICollectionGenericObjects.cs +++ b/Excavator/Excavator/CollectionGenericObjects/ICollectionGenericObjects.cs @@ -1,4 +1,6 @@ -namespace Excavator.CollectionGenericObjects; +using Excavator.Drawnings; + +namespace Excavator.CollectionGenericObjects; /// /// Интерфейс описания действий для набора хранимых объектов @@ -21,16 +23,18 @@ public interface ICollectionGenericObjects /// Добавление объекта в коллекцию /// /// Добавляемый объект + /// 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); /// /// Удаление объекта из коллекции с конкретной позиции @@ -56,4 +60,9 @@ public interface ICollectionGenericObjects /// /// Поэлементый вывод элементов коллекции IEnumerable GetItems(); + /// + /// Сортировка коллекции + /// + /// Сравнитель объектов + void CollectionSort(IComparer comparer); } \ No newline at end of file diff --git a/Excavator/Excavator/CollectionGenericObjects/ListGenericObjects.cs b/Excavator/Excavator/CollectionGenericObjects/ListGenericObjects.cs index dfdfc12..630830f 100644 --- a/Excavator/Excavator/CollectionGenericObjects/ListGenericObjects.cs +++ b/Excavator/Excavator/CollectionGenericObjects/ListGenericObjects.cs @@ -1,4 +1,6 @@ -using Excavator.Exceptions; +using Excavator.Drawnings; +using Excavator.Exceptions; +using System.Linq; namespace Excavator.CollectionGenericObjects; @@ -43,8 +45,16 @@ public class ListGenericObjects : ICollectionGenericObjects return _collection[position]; } - public int Insert(T obj) + public int Insert(T obj, IEqualityComparer? comparer = null) { + // TODO выброс ошибки, если переполнение + if (comparer != null) + { + if (_collection.Contains(obj, comparer)) + { + throw new ObjectAlreadyInCollectionException(); + } + } if (Count == _maxCount) { throw new CollectionOverflowException(Count); @@ -54,9 +64,17 @@ public class ListGenericObjects : ICollectionGenericObjects return _collection.Count; } - public int Insert(T obj, int position) + public int Insert(T obj, int position, IEqualityComparer? comparer = null) { - + // TODO выброс ошибки, если выход за границы списка + // TODO выброс ошибки, если переполнение + if (comparer != null) + { + if (_collection.Contains(obj, comparer)) + { + throw new ObjectAlreadyInCollectionException(); + } + } if (position < 0 || position > Count) { throw new PositionOutOfCollectionException(position); @@ -89,4 +107,8 @@ public class ListGenericObjects : ICollectionGenericObjects yield return _collection[i]; } } + public void CollectionSort(IComparer comparer) + { + _collection.Sort(comparer); + } } \ No newline at end of file diff --git a/Excavator/Excavator/CollectionGenericObjects/MassiveGenericObjects.cs b/Excavator/Excavator/CollectionGenericObjects/MassiveGenericObjects.cs index ce1751d..9f07f49 100644 --- a/Excavator/Excavator/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/Excavator/Excavator/CollectionGenericObjects/MassiveGenericObjects.cs @@ -1,4 +1,5 @@  +using Excavator.Drawnings; using Excavator.Exceptions; namespace Excavator.CollectionGenericObjects; @@ -62,8 +63,20 @@ public class MassiveGenericObjects : ICollectionGenericObjects return _collection[position]; } - public int Insert(T excavator) + public int Insert(T excavator, IEqualityComparer? comparer = null) { + if (comparer != null) + { + foreach (T? item in _collection) + { + if ((comparer as IEqualityComparer).Equals(excavator as DrawningTrackedVehicle, item as DrawningTrackedVehicle)) + { + throw new ObjectAlreadyInCollectionException(); + } + } + } + + for (int i = 0; i < Count; i++) { if (_collection[i] == null) @@ -75,9 +88,20 @@ public class MassiveGenericObjects : ICollectionGenericObjects throw new CollectionOverflowException(Count); } - public int Insert(T obj, int position) + public int Insert(T obj, int position, IEqualityComparer? comparer = null) { - + + if (comparer != null) + { + foreach (T? item in _collection) + { + if ((comparer as IEqualityComparer).Equals(obj as DrawningTrackedVehicle, item as DrawningTrackedVehicle)) + { + throw new ObjectAlreadyInCollectionException(); + } + } + } + if (position < 0 || position >= Count) { throw new PositionOutOfCollectionException(position); @@ -97,6 +121,7 @@ public class MassiveGenericObjects : ICollectionGenericObjects return i; } } + for (int i = position - 1; i >= 0; i--) { if (_collection[i] == null) @@ -133,4 +158,9 @@ public class MassiveGenericObjects : ICollectionGenericObjects yield return _collection[i]; } } + + public void CollectionSort(IComparer comparer) + { + Array.Sort(_collection, comparer); + } } \ No newline at end of file diff --git a/Excavator/Excavator/CollectionGenericObjects/StorageCollection.cs b/Excavator/Excavator/CollectionGenericObjects/StorageCollection.cs index dae655d..737a2fe 100644 --- a/Excavator/Excavator/CollectionGenericObjects/StorageCollection.cs +++ b/Excavator/Excavator/CollectionGenericObjects/StorageCollection.cs @@ -14,38 +14,41 @@ public class StorageCollection /// /// Словарь (хранилище) с коллекциями /// - readonly Dictionary> _storages; + readonly Dictionary> _storages; /// /// Возвращение списка названий коллекций /// - public List Keys => _storages.Keys.ToList(); + public List Keys => _storages.Keys.ToList(); /// /// Конструктор /// public StorageCollection() { - _storages = new Dictionary>(); + _storages = new Dictionary>(); } /// - /// Добавление коллекции в хранилище + /// добваление коллекции в хранилище /// - /// Название коллекции + /// название коллекции /// тип коллекции - public void AddCollection(string name, CollectionType collectionType) + public void AddCollection(CollectionInfo info) { - if (string.IsNullOrEmpty(name)) return; - if (_storages.ContainsKey(name)) return; - if (collectionType == CollectionType.None) return; - if (collectionType == CollectionType.Massive) + if (info == null || _storages.ContainsKey(info)) { - _storages[name] = new MassiveGenericObjects(); + return; } - else if (collectionType == CollectionType.List) + + if (info.CollectionType == CollectionType.Massive) { - _storages[name] = new ListGenericObjects(); + _storages.Add(info, new MassiveGenericObjects()); + } + + if (info.CollectionType == CollectionType.List) + { + _storages.Add(info, new ListGenericObjects()); } } @@ -53,14 +56,14 @@ public class StorageCollection /// Удаление коллекции /// /// - public void DelCollection(string name) + public void DelCollection(CollectionInfo info) { - if (name == null || !_storages.ContainsKey(name)) + if (info == null || !_storages.ContainsKey(info)) { return; } - _storages.Remove(name); + _storages.Remove(info); } /// @@ -68,13 +71,16 @@ public class StorageCollection /// /// Название коллекции /// - public ICollectionGenericObjects? this[string name] + public ICollectionGenericObjects? this[CollectionInfo info] { get { - if (name == null || !_storages.ContainsKey(name)) { return null; } - return _storages[name]; - + if (_storages.ContainsKey(info)) + { + return _storages[info]; + } + + return null; } } /// @@ -106,35 +112,34 @@ public class StorageCollection File.Delete(filename); } - using (StreamWriter writer = new StreamWriter(filename)) + using (StreamWriter sw = new StreamWriter(filename)) { - writer.Write(_collectionKey); - foreach (KeyValuePair> value in _storages) + sw.Write(_collectionKey); + + foreach (KeyValuePair> value in _storages) { - writer.Write(Environment.NewLine); + sw.Write(Environment.NewLine); // не сохраняем пустые коллекции if (value.Value.Count == 0) { continue; } - writer.Write(value.Key); - writer.Write(_separatorForKeyValue); - writer.Write(value.Value.GetCollectionType); - writer.Write(_separatorForKeyValue); - writer.Write(value.Value.MaxCount); - writer.Write(_separatorForKeyValue); + sw.Write(value.Key); + sw.Write(_separatorForKeyValue); + sw.Write(value.Value.MaxCount); + sw.Write(_separatorForKeyValue); foreach (T? item in value.Value.GetItems()) { string data = item?.GetDataForSave() ?? string.Empty; + if (string.IsNullOrEmpty(data)) { continue; } - - writer.Write(data); - writer.Write(_separatorItems); + sw.Write(data); + sw.Write(_separatorItems); } } } @@ -151,45 +156,43 @@ public class StorageCollection throw new FileNotFoundException("Файл не существует"); } - using (StreamReader reader = File.OpenText(filename)) + using (StreamReader sr = new(filename)) { - string? str = reader.ReadLine(); - if (str == null || str.Length == 0) + string line = sr.ReadLine(); + + if (line == null || line.Length == 0) { throw new FileFormatException("В файле нет данных"); } - if (!str.Equals(_collectionKey)) + if (!line.Equals(_collectionKey)) { + //если нет такой записи, то это не те данные throw new FileFormatException("В файле неверные данные"); } _storages.Clear(); - string? strs = ""; - while ((strs = reader.ReadLine()) != null) + while ((line = sr.ReadLine()) != null) { - string[] record = strs.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 InvalidOperationException("Не удалось создать коллекцию"); - } - collection.MaxCount = Convert.ToInt32(record[2]); - string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); + CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(record[0]) ?? + throw new Exception("Не удалось определить информацию коллекции: " + record[0]); + ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionInfo.CollectionType) ?? + throw new Exception("Не удалось создать коллекцию"); + collection.MaxCount = Convert.ToInt32(record[1]); + string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); foreach (string elem in set) { - if (elem?.CreateDrawningTrackedVehicle() is T ship) + if (elem?.CreateDrawningTrackedVehicle() is T machine) { try { - if (collection.Insert(ship) == -1) + if (collection.Insert(machine, new DrawningTrackedVehicleEqutables()) == -1) { throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]); } @@ -198,13 +201,18 @@ public class StorageCollection { throw new OverflowException("Коллекция переполнена", ex); } + catch (ObjectAlreadyInCollectionException ex) + { + throw new InvalidOperationException("Объект уже присутствует в коллекции", ex); + } } } - _storages.Add(record[0], collection); + _storages.Add(collectionInfo, collection); } - } } + + /// /// Создание коллекции по типу /// diff --git a/Excavator/Excavator/Drawnings/DrawningExcavatorEqutables.cs b/Excavator/Excavator/Drawnings/DrawningExcavatorEqutables.cs new file mode 100644 index 0000000..8f0467b --- /dev/null +++ b/Excavator/Excavator/Drawnings/DrawningExcavatorEqutables.cs @@ -0,0 +1,66 @@ +using Excavator.Entities; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; + +namespace Excavator.Drawnings; + +/// +/// Реализация сравнения двух объектов класса-прорисовки +/// +public class DrawningTrackedVehicleEqutables : IEqualityComparer +{ + public bool Equals(DrawningTrackedVehicle? x, DrawningTrackedVehicle? y) + { + if (x == null || x.EntityTrackedVehicle == null) + { + return false; + } + if (y == null || y.EntityTrackedVehicle == null) + { + return false; + } + if (x.GetType().Name != y.GetType().Name) + { + return false; + } + if (x.EntityTrackedVehicle.Speed != y.EntityTrackedVehicle.Speed) + { + return false; + } + if (x.EntityTrackedVehicle.Weight != y.EntityTrackedVehicle.Weight) + { + return false; + } + if (x.EntityTrackedVehicle.BodyColor != y.EntityTrackedVehicle.BodyColor) + { + return false; + } + if (x is DrawningExcavator && y is DrawningExcavator) + { + if ((x.EntityTrackedVehicle as EntityExcavator)?.AdditionalColor != + (y.EntityTrackedVehicle as EntityExcavator)?.AdditionalColor) + { + return false; + } + if ((x.EntityTrackedVehicle as EntityExcavator)?.Supports != + (y.EntityTrackedVehicle as EntityExcavator)?.Supports) + { + return false; + } + if ((x.EntityTrackedVehicle as EntityExcavator)?.Bucket != + (y.EntityTrackedVehicle as EntityExcavator)?.Bucket) + { + return false; + } + } + return true; + } + + public int GetHashCode([DisallowNull] DrawningTrackedVehicle? obj) + { + return obj.GetHashCode(); + } +} + + diff --git a/Excavator/Excavator/Drawnings/DrawningTrackedVehicleCompareByColor.cs b/Excavator/Excavator/Drawnings/DrawningTrackedVehicleCompareByColor.cs new file mode 100644 index 0000000..1dcf756 --- /dev/null +++ b/Excavator/Excavator/Drawnings/DrawningTrackedVehicleCompareByColor.cs @@ -0,0 +1,46 @@ +using Excavator.Entities; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Excavator.Drawnings; +/// +/// Сравнение по цвету, скорости, весу +/// +public class DrawningTrackedVehicleCompareByColor : IComparer +{ + public int Compare(DrawningTrackedVehicle? x, DrawningTrackedVehicle? y) + { + if (x == null || x.EntityTrackedVehicle == null) + { + return 1; + } + if (y == null || y.EntityTrackedVehicle == null) + { + return -1; + } + var bodyColorCompare = y.EntityTrackedVehicle.BodyColor.Name.CompareTo(x.EntityTrackedVehicle.BodyColor.Name); + if (bodyColorCompare != 0) + { + return bodyColorCompare; + } + if (x is DrawningExcavator && y is DrawningExcavator) + { + var additionalColorCompare = (y.EntityTrackedVehicle as EntityExcavator).AdditionalColor.Name.CompareTo( + (x.EntityTrackedVehicle as EntityExcavator).AdditionalColor.Name); + if (additionalColorCompare != 0) + { + return additionalColorCompare; + } + } + var speedCompare = y.EntityTrackedVehicle.Speed.CompareTo(x.EntityTrackedVehicle.Speed); + if (speedCompare != 0) + { + return speedCompare; + } + return y.EntityTrackedVehicle.Weight.CompareTo(x.EntityTrackedVehicle.Weight); + + } +} diff --git a/Excavator/Excavator/Drawnings/DrawningTrackedVehicleCompareByType.cs b/Excavator/Excavator/Drawnings/DrawningTrackedVehicleCompareByType.cs new file mode 100644 index 0000000..fadffcd --- /dev/null +++ b/Excavator/Excavator/Drawnings/DrawningTrackedVehicleCompareByType.cs @@ -0,0 +1,35 @@ +using Excavator.Drawnings; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Excavator.CollectionGenericObjects; +/// +/// Сравнение по типу, скорости, весу +/// +public class DrawningTrackedVehicleCompareByType : IComparer +{ + public int Compare(DrawningTrackedVehicle? x, DrawningTrackedVehicle? y) + { + if (x == null || x.EntityTrackedVehicle == null) + { + return 1; + } + if (y == null || y.EntityTrackedVehicle == null) + { + return -1; + } + if (x.GetType().Name != y.GetType().Name) + { + return y.GetType().Name.CompareTo(x.GetType().Name); + } + var speedCompare = y.EntityTrackedVehicle.Speed.CompareTo(x.EntityTrackedVehicle.Speed); + if (speedCompare != 0) + { + return speedCompare; + } + return y.EntityTrackedVehicle.Weight.CompareTo(x.EntityTrackedVehicle.Weight); + } +} \ No newline at end of file diff --git a/Excavator/Excavator/Exceptions/ObjectAlreadyInCollectionException.cs b/Excavator/Excavator/Exceptions/ObjectAlreadyInCollectionException.cs new file mode 100644 index 0000000..a4487e0 --- /dev/null +++ b/Excavator/Excavator/Exceptions/ObjectAlreadyInCollectionException.cs @@ -0,0 +1,21 @@ +using System.Runtime.Serialization; + +namespace Excavator.Exceptions; + +/// +/// Класс, описывающий ошибку переполнения коллекции +/// +[Serializable] +internal class ObjectAlreadyInCollectionException : ApplicationException +{ + public ObjectAlreadyInCollectionException(int index) : base("Такой объект уже присутствует в коллекции. Позиция " + index) { } + + public ObjectAlreadyInCollectionException() : base() { } + + public ObjectAlreadyInCollectionException(string message) : base(message) { } + + public ObjectAlreadyInCollectionException(string message, Exception exception) : base(message, exception) { } + + protected ObjectAlreadyInCollectionException(SerializationInfo info, StreamingContext contex) : base(info, contex) { } +} + diff --git a/Excavator/Excavator/FormTrackedVehicleCollection.Designer.cs b/Excavator/Excavator/FormTrackedVehicleCollection.Designer.cs index 752cd42..5e92ebb 100644 --- a/Excavator/Excavator/FormTrackedVehicleCollection.Designer.cs +++ b/Excavator/Excavator/FormTrackedVehicleCollection.Designer.cs @@ -52,6 +52,8 @@ LoadToolStripMenuItem = new ToolStripMenuItem(); saveFileDialog = new SaveFileDialog(); openFileDialog = new OpenFileDialog(); + buttonSortByType = new Button(); + buttonSortByColor = new Button(); groupBox1.SuspendLayout(); panelCompanyTools.SuspendLayout(); panelStorage.SuspendLayout(); @@ -75,6 +77,8 @@ // // panelCompanyTools // + panelCompanyTools.Controls.Add(buttonSortByColor); + panelCompanyTools.Controls.Add(buttonSortByType); panelCompanyTools.Controls.Add(buttonAddTrackedVehicle); panelCompanyTools.Controls.Add(buttonRefresh); panelCompanyTools.Controls.Add(buttonGoToCheck); @@ -82,9 +86,9 @@ panelCompanyTools.Controls.Add(buttonDelExcavator); panelCompanyTools.Dock = DockStyle.Bottom; panelCompanyTools.Enabled = false; - panelCompanyTools.Location = new Point(3, 514); + panelCompanyTools.Location = new Point(3, 409); panelCompanyTools.Name = "panelCompanyTools"; - panelCompanyTools.Size = new Size(215, 268); + panelCompanyTools.Size = new Size(215, 373); panelCompanyTools.TabIndex = 9; // // buttonAddTrackedVehicle @@ -294,6 +298,26 @@ openFileDialog.FileName = "openFileDialog1"; openFileDialog.Filter = "txt file | *.txt"; // + // buttonSortByType + // + buttonSortByType.Location = new Point(18, 256); + buttonSortByType.Name = "buttonSortByType"; + buttonSortByType.Size = new Size(171, 45); + buttonSortByType.TabIndex = 7; + buttonSortByType.Text = "Сортировка по типу"; + buttonSortByType.UseVisualStyleBackColor = true; + buttonSortByType.Click += buttonSortByType_Click; + // + // buttonSortByColor + // + buttonSortByColor.Location = new Point(18, 307); + buttonSortByColor.Name = "buttonSortByColor"; + buttonSortByColor.Size = new Size(171, 45); + buttonSortByColor.TabIndex = 8; + buttonSortByColor.Text = "Сортировка по цвету"; + buttonSortByColor.UseVisualStyleBackColor = true; + buttonSortByColor.Click += buttonSortByColor_Click; + // // FormTrackedVehicleCollection // AutoScaleDimensions = new SizeF(8F, 20F); @@ -343,5 +367,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/Excavator/Excavator/FormTrackedVehicleCollection.cs b/Excavator/Excavator/FormTrackedVehicleCollection.cs index 8f29df0..4758c41 100644 --- a/Excavator/Excavator/FormTrackedVehicleCollection.cs +++ b/Excavator/Excavator/FormTrackedVehicleCollection.cs @@ -174,33 +174,34 @@ public partial class FormTrackedVehicleCollection : Form pictureBox.Image = _company.Show(); } /// - /// Добавление коллекции - /// - /// - /// - private void buttonCollectionAdd_Click(object sender, EventArgs e) + /// Добавление коллекции + /// + /// + /// + private void buttonCollectionAdd_Click(object sender, EventArgs e) + { + if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked)) { - if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked)) - { - MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - _logger.LogError("Ошибка: Заполнены не все данные для добавления коллекции"); - return; - } - - CollectionType collectionType = CollectionType.None; - if (radioButtonMassive.Checked) - { - collectionType = CollectionType.Massive; - } - else if (radioButtonList.Checked) - { - collectionType = CollectionType.List; - } - - _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); - _logger.LogInformation($"Добавлена коллекция: {textBoxCollectionName.Text} типа: {collectionType}"); - RerfreshListBoxItems(); + MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogError("Ошибка: Заполнены не все данные для добавления коллекции"); + return; } + + CollectionType collectionType = CollectionType.None; + if (radioButtonMassive.Checked) + { + collectionType = CollectionType.Massive; + } + else if (radioButtonList.Checked) + { + collectionType = CollectionType.List; + } + CollectionInfo collectionInfo = new CollectionInfo(textBoxCollectionName.Text, collectionType, string.Empty); + + _storageCollection.AddCollection(collectionInfo); + _logger.LogInformation($"Добавлена коллекция: {textBoxCollectionName.Text} типа: {collectionType}"); + RerfreshListBoxItems(); + } /// /// Удаление коллекции /// @@ -213,13 +214,15 @@ public partial class FormTrackedVehicleCollection : Form MessageBox.Show("Коллекция не выбрана"); return; } - if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) + + if (MessageBox.Show("Вы уверены, что хотите удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) { return; } - _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString()); - _logger.LogInformation($"Удалена коллекция: {listBoxCollection.SelectedItem.ToString()}"); + CollectionInfo collectionInfo = new CollectionInfo(listBoxCollection.SelectedItem.ToString(), CollectionType.None, string.Empty); + _storageCollection.DelCollection(collectionInfo); + _logger.LogInformation($"Удалена коллекция: {listBoxCollection.SelectedItem.ToString()}"); RerfreshListBoxItems(); } /// @@ -230,7 +233,7 @@ public partial class FormTrackedVehicleCollection : 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); @@ -251,7 +254,8 @@ public partial class FormTrackedVehicleCollection : Form return; } - ICollectionGenericObjects? collection = _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty]; + CollectionInfo collectionInfo = new CollectionInfo(listBoxCollection.SelectedItem.ToString(), CollectionType.None, string.Empty); + ICollectionGenericObjects? collection = _storageCollection[collectionInfo]; if (collection == null) { MessageBox.Show("Коллекция не проинициализирована"); @@ -264,7 +268,6 @@ public partial class FormTrackedVehicleCollection : Form _company = new Garage(pictureBox.Width, pictureBox.Height, collection); break; } - panelCompanyTools.Enabled = true; RerfreshListBoxItems(); } @@ -314,7 +317,33 @@ public partial class FormTrackedVehicleCollection : Form } } } + /// + /// Сортировка по типу + /// + /// + /// + private void buttonSortByType_Click(object sender, EventArgs e) + { + CompareTrackedVehicles(new DrawningTrackedVehicleCompareByType()); + } + /// + /// Сортировка по цвету + /// + /// + /// + private void buttonSortByColor_Click(object sender, EventArgs e) + { + CompareTrackedVehicles(new DrawningTrackedVehicleCompareByColor()); + } - + private void CompareTrackedVehicles(IComparer comparer) + { + if (_company == null) + { + return; + } + _company.Sort(comparer); + pictureBox.Image = _company.Show(); + } }