diff --git a/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObject/AbstractCompany.cs b/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObject/AbstractCompany.cs index 4ecbbf9..24e25b8 100644 --- a/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObject/AbstractCompany.cs +++ b/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObject/AbstractCompany.cs @@ -62,7 +62,18 @@ public abstract class AbstractCompany /// public static int operator +(AbstractCompany company, DrawningTruck truck) { - return company._collection.Insert(truck,0); + try + { + return company._collection.Insert(truck, 0, new DrawningTruckEqutables()); + } + catch (ObjectAlreadyInCollectionException) + { + return -1; + } + catch (CollectionOverflowException) + { + return -1; + } } /// @@ -130,4 +141,11 @@ public abstract class AbstractCompany /// protected abstract void SetObjectsPosition(); + /// + /// Сортировка + /// + /// Сравнитель объектов + public void Sort(IComparer comparer) => _collection?.CollectionSort(comparer); + + } diff --git a/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObject/CollectionInfo.cs b/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObject/CollectionInfo.cs new file mode 100644 index 0000000..9011222 --- /dev/null +++ b/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObject/CollectionInfo.cs @@ -0,0 +1,52 @@ + + +namespace ProjectDumpTruck.CollectionGenericObject; + +public class CollectionInfo : IEquatable +{ + + public string Name { get; set; } + + public CollectionType CollectionType { get; set; } + + public string Description { get; set; } + + private static readonly string _separator = "-"; + + public CollectionInfo(string name, CollectionType collectionType, string description) + { + Name = name; + CollectionType = collectionType; + Description = description; + } + + public static CollectionInfo? GetCollectionInfo(string data) + { + string[] strs = data.Split(_separator, StringSplitOptions.RemoveEmptyEntries); + + if (strs.Length<1 || strs.Length>3) return null; + + return new CollectionInfo(strs[0], (CollectionType)Enum.Parse(typeof(CollectionType), strs[1]), + strs.Length > 2 ? strs[2] : string.Empty); + } + + public override string ToString() + { + return Name + _separator + CollectionType + _separator + Description; + } + + public bool Equals(CollectionInfo? other) + { + return Name == other?.Name; + } + + public override bool Equals(object? obj) + { + return Equals(obj as CollectionInfo); + } + + public override int GetHashCode() + { + return Name.GetHashCode(); + } +} diff --git a/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObject/ICollectionGenericObject.cs b/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObject/ICollectionGenericObject.cs index 99658f2..aed37a8 100644 --- a/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObject/ICollectionGenericObject.cs +++ b/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObject/ICollectionGenericObject.cs @@ -1,4 +1,5 @@ -using System; +using ProjectDumpTruck.Drawnings; +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -25,7 +26,7 @@ public interface ICollectionGenericObject /// /// Добавляемый объект /// true - вставка прошла удачно, false - вставка не удалась - int Insert(T obj); + int Insert(T obj, IEqualityComparer? comparer = null); /// /// Добавление объекта на конкретную позиуцию @@ -33,7 +34,7 @@ public interface ICollectionGenericObject /// Добавляемый объектПозиция /// true - вставка прошла успешна, false - вставка не удалась - int Insert(T obj, int position); + int Insert(T obj, int position, IEqualityComparer? comparer = null); /// /// Удаление объекта из коллекции с конкретной позиции @@ -59,4 +60,10 @@ public interface ICollectionGenericObject /// /// IEnumerable GetItems(); + + /// + /// Сортировка коллекции + /// + /// Сравнитель объектов + void CollectionSort(IComparer comparer); } diff --git a/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObject/ListGenericObjects.cs b/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObject/ListGenericObjects.cs index 94d269a..76e1454 100644 --- a/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObject/ListGenericObjects.cs +++ b/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObject/ListGenericObjects.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; +using ProjectDumpTruck.Drawnings; using ProjectDumpTruck.Exceptions; @@ -58,18 +59,26 @@ public class ListGenericObjects : ICollectionGenericObject return _collection[position]; } - public int Insert(T obj) + public int Insert(T obj, IEqualityComparer? comparer = null) { if (Count == _maxCount) { throw new CollectionOverflowException(Count); } + for (int i = 0; i < Count; i++) + { + if (comparer.Equals((_collection[i] as DrawningTruck), (obj as DrawningTruck))) + { + throw new ObjectAlreadyInCollectionException(i); + } + } + _collection.Add(obj); return _collection.Count; } - public int Insert(T obj, int position) + public int Insert(T obj, int position, IEqualityComparer? comparer = null) { if (position < 0 || position > Count) { @@ -79,6 +88,13 @@ public class ListGenericObjects : ICollectionGenericObject { throw new CollectionOverflowException(Count); } + for (int i = 0; i < Count; i++) + { + if (comparer.Equals((_collection[i] as DrawningTruck), (obj as DrawningTruck))) + { + throw new ObjectAlreadyInCollectionException(i); + } + } _collection.Insert(position, obj); return position; @@ -101,4 +117,9 @@ public class ListGenericObjects : ICollectionGenericObject { for (int i = 0; i < Count; i++) yield return _collection[i]; } + + public void CollectionSort(IComparer comparer) + { + _collection.Sort(comparer); + } } diff --git a/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObject/MassiveGenericObjects.cs b/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObject/MassiveGenericObjects.cs index db74384..a9998a3 100644 --- a/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObject/MassiveGenericObjects.cs +++ b/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObject/MassiveGenericObjects.cs @@ -1,9 +1,11 @@  using System; +using System.Collections; using System.Collections.Generic; using System.Linq; using System.Reflection.Metadata.Ecma335; using System.Text; using System.Threading.Tasks; +using ProjectDumpTruck.Drawnings; using ProjectDumpTruck.Exceptions; namespace ProjectDumpTruck.CollectionGenericObject; @@ -69,9 +71,16 @@ public class MassiveGenericObjects : ICollectionGenericObject return _collection[position]; } - public int Insert(T obj) + public int Insert(T obj, IEqualityComparer? comparer = null) { - // TODO вставка в свободное место набора + for (int i = 0; i < Count; i++) + { + if (comparer.Equals((_collection[i] as DrawningTruck), (obj as DrawningTruck))) + { + throw new ObjectAlreadyInCollectionException(i); + } + } + for (int i = 0; i < Count; i++) { if (_collection[i] == null) @@ -84,13 +93,21 @@ public class MassiveGenericObjects : ICollectionGenericObject 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); } + for (int i = 0; i < Count; i++) + { + if (comparer.Equals((_collection[i] as DrawningTruck), (obj as DrawningTruck))) + { + throw new ObjectAlreadyInCollectionException(i); + } + } + if (_collection[position] == null) { _collection[position] = obj; @@ -139,4 +156,9 @@ public class MassiveGenericObjects : ICollectionGenericObject { for (int i = 0; i < _collection.Length; i++) yield return _collection[i]; } + + public void CollectionSort(IComparer comparer) + { + Array.Sort(_collection, comparer); + } } \ No newline at end of file diff --git a/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObject/StorageCollection.cs b/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObject/StorageCollection.cs index b9ced44..d6d2db5 100644 --- a/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObject/StorageCollection.cs +++ b/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObject/StorageCollection.cs @@ -15,12 +15,12 @@ public class StorageCollection /// /// Словарь (хранилище) с коллекциями /// - readonly Dictionary> _storages; + readonly Dictionary> _storages; /// /// Возвращение списка названий коллекций /// - public List Keys => _storages.Keys.ToList(); + public List Keys => _storages.Keys.ToList(); /// /// Ключевое слово, с которого должен начинаться файл @@ -41,7 +41,7 @@ public class StorageCollection /// public StorageCollection() { - _storages = new Dictionary>(); + _storages = new Dictionary>(); } /// @@ -49,21 +49,21 @@ public class StorageCollection /// /// Название коллекции /// Тип коллекции - public void AddCollection(string name, CollectionType collectionType) + public void AddCollection(CollectionInfo info) { - if (name == null || _storages.ContainsKey(name)) + if (info == null || _storages.ContainsKey(info)) { return; } - if (collectionType == CollectionType.Massive) + if (info.CollectionType == CollectionType.Massive) { - _storages.Add(name, new MassiveGenericObjects()); + _storages.Add(info, new MassiveGenericObjects()); } - if (collectionType == CollectionType.List) + if (info.CollectionType == CollectionType.List) { - _storages.Add(name, new ListGenericObjects()); + _storages.Add(info, new ListGenericObjects()); } } @@ -71,14 +71,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); } /// @@ -86,13 +86,13 @@ public class StorageCollection /// /// Название коллекции /// - public ICollectionGenericObject? this[string name] + public ICollectionGenericObject? this[CollectionInfo info] { get { - if (_storages.ContainsKey(name)) + if (_storages.ContainsKey(info)) { - return _storages[name]; + return _storages[info]; } return null; @@ -109,7 +109,7 @@ public class StorageCollection { sw.Write(_collectionKey); - foreach (KeyValuePair> value in _storages) + foreach (KeyValuePair> value in _storages) { sw.Write(Environment.NewLine); // не сохраняем пустые коллекции @@ -117,8 +117,6 @@ public class StorageCollection sw.Write(value.Key); sw.Write(_separatorForKeyValue); - sw.Write(value.Value.GetCollectionType); - sw.Write(_separatorForKeyValue); sw.Write(value.Value.MaxCount); sw.Write(_separatorForKeyValue); @@ -142,42 +140,49 @@ public class StorageCollection /// /// Путь и имя файла /// true - загрузка прошла успешно, false - ошибка при загрузке данных - public bool LoadData(string filename) + public void LoadData(string filename) { - if (!File.Exists(filename)) throw new FileNotFoundException("Файл не существует"); + if (!File.Exists(filename)) + { + throw new FileNotFoundException("Файл не существует"); + } using (StreamReader sr = new(filename)) { string line = sr.ReadLine(); - if (line == null || line.Length == 0) throw new FileFormatException("В файле нет данных"); ; - - if (!line.Equals(_collectionKey)) throw new FileFormatException("В файле неверные данные"); - + if (line == null || line.Length == 0) + { + throw new FileFormatException("В файле нет данных"); + } + if (!line.Equals(_collectionKey)) + { + throw new FileFormatException("В файле неверные данные"); + } _storages.Clear(); while ((line = sr.ReadLine()) != null) { string[] record = line.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); - if (record.Length != 4) + if (record.Length != 3) { continue; } - CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]); - ICollectionGenericObject? collection = StorageCollection.CreateCollection(collectionType); + CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(record[0]) ?? + throw new Exception("Не удалось определить информацию коллекции: " + record[0]); + ICollectionGenericObject? collection = StorageCollection.CreateCollection(collectionInfo.CollectionType) ?? + throw new Exception("Не удалось создать коллекцию"); + collection.MaxCount = Convert.ToInt32(record[1]); - if (collection == null) throw new InvalidOperationException("Не удалось создать коллекцию"); - - collection.MaxCount = Convert.ToInt32(record[2]); - string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); + string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); foreach (string elem in set) { if (elem?.CreateDrawningTruck() is T truck) { try { - if (collection.Insert(truck) == -1) + if (collection.Insert(truck, new DrawningTruckEqutables()) == -1) { throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]); } @@ -186,15 +191,18 @@ public class StorageCollection { throw new OverflowException("Коллекция переполнена", ex); } + catch (ObjectAlreadyInCollectionException ex) + { + throw new InvalidOperationException("Объект уже присутствует в коллекции", ex); + } } } - _storages.Add(record[0], collection); + _storages.Add(collectionInfo, collection); } } - - return true; } + /// /// Создание коллекции по типу /// diff --git a/ProjectDumpTruck/ProjectDumpTruck/Drawnings/DrawningTruckCompareByColor.cs b/ProjectDumpTruck/ProjectDumpTruck/Drawnings/DrawningTruckCompareByColor.cs new file mode 100644 index 0000000..cd63cd8 --- /dev/null +++ b/ProjectDumpTruck/ProjectDumpTruck/Drawnings/DrawningTruckCompareByColor.cs @@ -0,0 +1,43 @@ + +using ProjectDumpTruck.Entities; + +namespace ProjectDumpTruck.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; + } + if (x is DrawningDumpTruck && y is DrawningDumpTruck) + { + var additionalColorCompare = (y.EntityTruck as EntityDumpTruck).AdditionalColor.Name.CompareTo( + (x.EntityTruck as EntityDumpTruck).AdditionalColor.Name); + if (additionalColorCompare != 0) + { + return additionalColorCompare; + } + } + 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/ProjectDumpTruck/ProjectDumpTruck/Drawnings/DrawningTruckCompareByType.cs b/ProjectDumpTruck/ProjectDumpTruck/Drawnings/DrawningTruckCompareByType.cs new file mode 100644 index 0000000..c508983 --- /dev/null +++ b/ProjectDumpTruck/ProjectDumpTruck/Drawnings/DrawningTruckCompareByType.cs @@ -0,0 +1,30 @@ +namespace ProjectDumpTruck.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/ProjectDumpTruck/ProjectDumpTruck/Drawnings/DrawningTruckEqutables.cs b/ProjectDumpTruck/ProjectDumpTruck/Drawnings/DrawningTruckEqutables.cs new file mode 100644 index 0000000..29a841a --- /dev/null +++ b/ProjectDumpTruck/ProjectDumpTruck/Drawnings/DrawningTruckEqutables.cs @@ -0,0 +1,60 @@ +using ProjectDumpTruck.Entities; +using System.Diagnostics.CodeAnalysis; + +namespace ProjectDumpTruck.Drawnings; + +public class DrawningTruckEqutables : 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 DrawningDumpTruck && y is DrawningDumpTruck) + { + // TODO доделать логику сравнения дополнительных параметров + if ((x.EntityTruck as EntityDumpTruck)?.AdditionalColor != + (y.EntityTruck as EntityDumpTruck)?.AdditionalColor) + { + return false; + } + if ((x.EntityTruck as EntityDumpTruck)?.Awning != + (y.EntityTruck as EntityDumpTruck)?.Awning) + { + return false; + } + if ((x.EntityTruck as EntityDumpTruck)?.Tent != + (y.EntityTruck as EntityDumpTruck)?.Tent) + { + return false; + } + } + return true; + } + + public int GetHashCode([DisallowNull] DrawningTruck? obj) + { + return obj.GetHashCode(); + } +} diff --git a/ProjectDumpTruck/ProjectDumpTruck/Exceptions/ObjectAlreadyInCollectionException.cs b/ProjectDumpTruck/ProjectDumpTruck/Exceptions/ObjectAlreadyInCollectionException.cs new file mode 100644 index 0000000..7d4e80f --- /dev/null +++ b/ProjectDumpTruck/ProjectDumpTruck/Exceptions/ObjectAlreadyInCollectionException.cs @@ -0,0 +1,19 @@ + +using System.Runtime.Serialization; + +namespace ProjectDumpTruck.Exceptions; + +[Serializable] +internal class ObjectAlreadyInCollectionException : ApplicationException +{ + public ObjectAlreadyInCollectionException(int i) : base("Такой объект уже есть в коллекции. Позиция " + i) { } + + 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/ProjectDumpTruck/ProjectDumpTruck/FormTruckCollection.Designer.cs b/ProjectDumpTruck/ProjectDumpTruck/FormTruckCollection.Designer.cs index fdafef4..eb7d2ae 100644 --- a/ProjectDumpTruck/ProjectDumpTruck/FormTruckCollection.Designer.cs +++ b/ProjectDumpTruck/ProjectDumpTruck/FormTruckCollection.Designer.cs @@ -52,6 +52,8 @@ loadToolStripMenuItem = new ToolStripMenuItem(); saveFileDialog = new SaveFileDialog(); openFileDialog = new OpenFileDialog(); + buttonSortByColor = new Button(); + buttonSortByType = new Button(); groupBoxTools.SuspendLayout(); panelStorage.SuspendLayout(); panelCompanyTools.SuspendLayout(); @@ -68,7 +70,7 @@ groupBoxTools.Dock = DockStyle.Right; groupBoxTools.Location = new Point(888, 28); groupBoxTools.Name = "groupBoxTools"; - groupBoxTools.Size = new Size(238, 660); + groupBoxTools.Size = new Size(238, 741); groupBoxTools.TabIndex = 0; groupBoxTools.TabStop = false; groupBoxTools.Text = "Инструменты"; @@ -164,6 +166,8 @@ // // panelCompanyTools // + panelCompanyTools.Controls.Add(buttonSortByColor); + panelCompanyTools.Controls.Add(buttonSortByType); panelCompanyTools.Controls.Add(buttonAddTruck); panelCompanyTools.Controls.Add(buttonRemoveTruck); panelCompanyTools.Controls.Add(buttonRefresh); @@ -171,14 +175,14 @@ panelCompanyTools.Controls.Add(maskedTextBoxPosition); panelCompanyTools.Dock = DockStyle.Bottom; panelCompanyTools.Enabled = false; - panelCompanyTools.Location = new Point(3, 357); + panelCompanyTools.Location = new Point(3, 385); panelCompanyTools.Name = "panelCompanyTools"; - panelCompanyTools.Size = new Size(232, 300); + panelCompanyTools.Size = new Size(232, 353); panelCompanyTools.TabIndex = 10; // // buttonAddTruck // - buttonAddTruck.Location = new Point(3, 35); + buttonAddTruck.Location = new Point(0, 3); buttonAddTruck.Name = "buttonAddTruck"; buttonAddTruck.Size = new Size(226, 42); buttonAddTruck.TabIndex = 0; @@ -187,7 +191,7 @@ // // buttonRemoveTruck // - buttonRemoveTruck.Location = new Point(3, 138); + buttonRemoveTruck.Location = new Point(3, 84); buttonRemoveTruck.Name = "buttonRemoveTruck"; buttonRemoveTruck.Size = new Size(226, 48); buttonRemoveTruck.TabIndex = 4; @@ -197,7 +201,7 @@ // // buttonRefresh // - buttonRefresh.Location = new Point(3, 246); + buttonRefresh.Location = new Point(0, 192); buttonRefresh.Name = "buttonRefresh"; buttonRefresh.Size = new Size(226, 48); buttonRefresh.TabIndex = 6; @@ -207,7 +211,7 @@ // // buttonGoToCheck // - buttonGoToCheck.Location = new Point(3, 192); + buttonGoToCheck.Location = new Point(3, 138); buttonGoToCheck.Name = "buttonGoToCheck"; buttonGoToCheck.Size = new Size(226, 48); buttonGoToCheck.TabIndex = 5; @@ -217,7 +221,7 @@ // // maskedTextBoxPosition // - maskedTextBoxPosition.Location = new Point(3, 105); + maskedTextBoxPosition.Location = new Point(3, 51); maskedTextBoxPosition.Mask = "00"; maskedTextBoxPosition.Name = "maskedTextBoxPosition"; maskedTextBoxPosition.Size = new Size(226, 27); @@ -241,7 +245,7 @@ pictureBox.Dock = DockStyle.Fill; pictureBox.Location = new Point(0, 28); pictureBox.Name = "pictureBox"; - pictureBox.Size = new Size(888, 660); + pictureBox.Size = new Size(888, 741); pictureBox.TabIndex = 1; pictureBox.TabStop = false; // @@ -286,11 +290,31 @@ // openFileDialog.Filter = "txt file | *.txt"; // + // buttonSortByColor + // + buttonSortByColor.Location = new Point(0, 300); + buttonSortByColor.Name = "buttonSortByColor"; + buttonSortByColor.Size = new Size(226, 48); + buttonSortByColor.TabIndex = 8; + buttonSortByColor.Text = "Сортировка по цвету"; + buttonSortByColor.UseVisualStyleBackColor = true; + buttonSortByColor.Click += ButtonSortByColor_Click; + // + // buttonSortByType + // + buttonSortByType.Location = new Point(3, 246); + buttonSortByType.Name = "buttonSortByType"; + buttonSortByType.Size = new Size(226, 48); + buttonSortByType.TabIndex = 7; + buttonSortByType.Text = "Сортировка по типу"; + buttonSortByType.UseVisualStyleBackColor = true; + buttonSortByType.Click += ButtonSortByType_Click; + // // FormTruckCollection // AutoScaleDimensions = new SizeF(8F, 20F); AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(1126, 688); + ClientSize = new Size(1126, 769); Controls.Add(pictureBox); Controls.Add(groupBoxTools); Controls.Add(menuStrip); @@ -335,5 +359,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/ProjectDumpTruck/ProjectDumpTruck/FormTruckCollection.cs b/ProjectDumpTruck/ProjectDumpTruck/FormTruckCollection.cs index 82bfa83..ca32522 100644 --- a/ProjectDumpTruck/ProjectDumpTruck/FormTruckCollection.cs +++ b/ProjectDumpTruck/ProjectDumpTruck/FormTruckCollection.cs @@ -37,7 +37,7 @@ public partial class FormTruckCollection : Form /// /// Конструктор /// - public FormTruckCollection(ILogger logger) + public FormTruckCollection(ILogger logger) { InitializeComponent(); _storageCollection = new(); @@ -72,25 +72,35 @@ public partial class FormTruckCollection : Form /// private void SetTruck(DrawningTruck truck) { + if (_company == null || truck == null) + { + return; + } + try { - if (_company == null || truck == null) - { - return; - } - + if (_company + truck != -1) { MessageBox.Show("Объект добавлен"); _logger.LogInformation($"Добавлен объект {truck.GetDataForSave()}"); pictureBox.Image = _company.Show(); } + else + { + MessageBox.Show("Не удалось добавить объект"); + } } catch (CollectionOverflowException ex) { MessageBox.Show(ex.Message); _logger.LogWarning($"Ошибка: {ex.Message}"); } + catch (ArgumentException ex) + { + MessageBox.Show(ex.Message); + _logger.LogWarning($"Ошибка: {ex.Message}"); + } } /// @@ -202,7 +212,9 @@ public partial class FormTruckCollection : Form collectionType = CollectionType.List; } - _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); + CollectionInfo collectionInfo = new CollectionInfo(textBoxCollectionName.Text, collectionType, string.Empty); + + _storageCollection.AddCollection(collectionInfo); _logger.LogInformation($"Добавлена коллекция: {textBoxCollectionName.Text} типа: {collectionType}"); RefreshListBoxItems(); } @@ -212,7 +224,7 @@ public partial class FormTruckCollection : 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); @@ -232,7 +244,8 @@ public partial class FormTruckCollection : Form { return; } - _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString()); + CollectionInfo collectionInfo = new CollectionInfo(listBoxCollection.SelectedItem.ToString(), CollectionType.None, string.Empty); + _storageCollection.DelCollection(collectionInfo); _logger.LogInformation($"Удалена коллекция: {listBoxCollection.SelectedItem.ToString()}"); RefreshListBoxItems(); } @@ -245,7 +258,8 @@ public partial class FormTruckCollection : Form return; } - ICollectionGenericObject? collection = _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty]; + CollectionInfo collectionInfo = new CollectionInfo(listBoxCollection.SelectedItem.ToString(), CollectionType.None, string.Empty); + ICollectionGenericObject? collection = _storageCollection[collectionInfo]; if (collection == null) { MessageBox.Show("Коллекция не проинициализирована"); @@ -308,6 +322,24 @@ 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(); + } } diff --git a/ProjectDumpTruck/ProjectDumpTruck/FormTruckCollection.resx b/ProjectDumpTruck/ProjectDumpTruck/FormTruckCollection.resx index ee1748a..9d4ca22 100644 --- a/ProjectDumpTruck/ProjectDumpTruck/FormTruckCollection.resx +++ b/ProjectDumpTruck/ProjectDumpTruck/FormTruckCollection.resx @@ -126,4 +126,7 @@ 310, 17 + + 55 + \ No newline at end of file