diff --git a/ProjectElectricLocomotive/ProjectElectricLocomotive/CollectionGenericObjects/AbstractCompany.cs b/ProjectElectricLocomotive/ProjectElectricLocomotive/CollectionGenericObjects/AbstractCompany.cs index e64da79..24c5cc2 100644 --- a/ProjectElectricLocomotive/ProjectElectricLocomotive/CollectionGenericObjects/AbstractCompany.cs +++ b/ProjectElectricLocomotive/ProjectElectricLocomotive/CollectionGenericObjects/AbstractCompany.cs @@ -59,9 +59,9 @@ public abstract class AbstractCompany /// Компания /// Добавляемый объект /// - public static int operator +(AbstractCompany company, DrawningLocomotive truck) + public static int operator +(AbstractCompany company, DrawningLocomotive locomotive) { - return company._collection.Insert(truck); + return company._collection.Insert(locomotive, new DrawningLocomotiveEqutables()); } // @@ -109,7 +109,10 @@ public abstract class AbstractCompany } return bitmap; } - + /// Сортировка + /// + /// Сравнитель объектов + public void Sort(IComparer comparer) => _collection?.CollectionSort(comparer); /// /// Вывод заднего фона /// diff --git a/ProjectElectricLocomotive/ProjectElectricLocomotive/CollectionGenericObjects/CollectionInfo.cs b/ProjectElectricLocomotive/ProjectElectricLocomotive/CollectionGenericObjects/CollectionInfo.cs new file mode 100644 index 0000000..e1fec2b --- /dev/null +++ b/ProjectElectricLocomotive/ProjectElectricLocomotive/CollectionGenericObjects/CollectionInfo.cs @@ -0,0 +1,79 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectElectricLocomotive.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; + else 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/ProjectElectricLocomotive/ProjectElectricLocomotive/CollectionGenericObjects/ICollectionGenericObjects.cs b/ProjectElectricLocomotive/ProjectElectricLocomotive/CollectionGenericObjects/ICollectionGenericObjects.cs index 9eb3578..889aa54 100644 --- a/ProjectElectricLocomotive/ProjectElectricLocomotive/CollectionGenericObjects/ICollectionGenericObjects.cs +++ b/ProjectElectricLocomotive/ProjectElectricLocomotive/CollectionGenericObjects/ICollectionGenericObjects.cs @@ -1,4 +1,5 @@ -using System; +using ProjectElectricLocomotive.Drawnings; +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -11,7 +12,7 @@ namespace ProjectElectricLocomotive.CollectionGenericObjects; /// /// Параметр: ограничение - ссылочный тип public interface ICollectionGenericObjects - where T : class + where T : DrawningLocomotive { /// /// Количество объектов в коллекции @@ -28,13 +29,13 @@ public interface ICollectionGenericObjects /// /// Добавляемый объект /// true - вставка прошла удачно, false - вставка не удалась - int Insert(T obj); + int Insert(T obj, IEqualityComparer? comparer = null); /// /// Добавление объекта в коллекцию на конкретную позицию /// /// Добавляемый объект /// Позиция /// true - вставка прошла удачно, false - вставка не удалась - int Insert(T obj, int position); + int Insert(T obj, int position, IEqualityComparer? comparer = null); /// /// Удаление объекта из коллекции с конкретной позиции /// @@ -58,5 +59,10 @@ public interface ICollectionGenericObjects /// /// IEnumerable GetItems(); + /// + /// Сортировка коллекции + /// + /// + void CollectionSort(IComparer comparer); } \ No newline at end of file diff --git a/ProjectElectricLocomotive/ProjectElectricLocomotive/CollectionGenericObjects/ListGenericObjects.cs b/ProjectElectricLocomotive/ProjectElectricLocomotive/CollectionGenericObjects/ListGenericObjects.cs index 0af16a8..e745f3d 100644 --- a/ProjectElectricLocomotive/ProjectElectricLocomotive/CollectionGenericObjects/ListGenericObjects.cs +++ b/ProjectElectricLocomotive/ProjectElectricLocomotive/CollectionGenericObjects/ListGenericObjects.cs @@ -1,4 +1,5 @@ -using ProjectElectricLocomotive.Exceptions; +using ProjectElectricLocomotive.Drawnings; +using ProjectElectricLocomotive.Exceptions; using System; using System.Collections.Generic; using System.Linq; @@ -8,7 +9,7 @@ using System.Threading.Tasks; namespace ProjectElectricLocomotive.CollectionGenericObjects; public class ListGenericObjects : ICollectionGenericObjects - where T : class + where T : DrawningLocomotive { /// /// Список объектов, которые храним @@ -60,20 +61,22 @@ public class ListGenericObjects : ICollectionGenericObjects } } - public int Insert(T obj) + public int Insert(T obj, IEqualityComparer? comparer = null) { - + if (_collection.Contains(obj, comparer)) throw new AlreadyExistingObject(obj.GetDataForSave()); if (Count == _maxCount) throw new CollectionOwerflowException(Count); _collection.Add(obj); return Count; } - public int Insert(T obj, int position) + public int Insert(T obj, int position, IEqualityComparer? comparer = null) { // проверка, что не превышено максимальное количество элементов // проверка позиции // вставка по позиции + if (_collection.Contains(obj, comparer)) throw new AlreadyExistingObject(obj.GetDataForSave()); + if (position > MaxCount) throw new CollectionOwerflowException(position); if (obj == null) throw new ArgumentNullException(nameof(obj)); @@ -107,4 +110,10 @@ public class ListGenericObjects : ICollectionGenericObjects yield return _collection[i]; } } + + public void CollectionSort(IComparer comparer) + { + _collection.Sort(comparer); + } + } diff --git a/ProjectElectricLocomotive/ProjectElectricLocomotive/CollectionGenericObjects/MassiveGenericObjects.cs b/ProjectElectricLocomotive/ProjectElectricLocomotive/CollectionGenericObjects/MassiveGenericObjects.cs index c09300d..5548cab 100644 --- a/ProjectElectricLocomotive/ProjectElectricLocomotive/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/ProjectElectricLocomotive/ProjectElectricLocomotive/CollectionGenericObjects/MassiveGenericObjects.cs @@ -1,4 +1,5 @@ -using ProjectElectricLocomotive.Exceptions; +using ProjectElectricLocomotive.Drawnings; +using ProjectElectricLocomotive.Exceptions; using System; using System.Collections.Generic; using System.Linq; @@ -12,7 +13,7 @@ namespace ProjectElectricLocomotive.CollectionGenericObjects; /// /// Параметр: ограничение - ссылочный тип public class MassiveGenericObjects : ICollectionGenericObjects - where T : class + where T : DrawningLocomotive { /// /// Массив объектов, которые храним @@ -66,9 +67,10 @@ public class MassiveGenericObjects : ICollectionGenericObjects throw new PositionOutOfCollectionException(position); } } - public int Insert(T obj) + public int Insert(T obj, IEqualityComparer? comparer = null) { // вставка в свободное место набора + if (_collection.Contains(obj, comparer)) throw new AlreadyExistingObject(obj.GetDataForSave()); for (int i = 0; i < Count; ++i) { if (_collection[i] == null) @@ -81,17 +83,14 @@ public class MassiveGenericObjects : ICollectionGenericObjects } - public int Insert(T obj, int position) + public int Insert(T obj, int position, IEqualityComparer? comparer = null) { // проверка позиции // проверка, что элемент массива по этой позиции пустой, если нет, то // ищется свободное место после этой позиции и идет вставка туда, если нет после, ищем до // вставка - if (position >= Count || position < 0) - { - return -1; - } + if (_collection.Contains(obj, comparer)) throw new AlreadyExistingObject(obj.GetDataForSave()); if (_collection[position] == null) { @@ -146,4 +145,14 @@ public class MassiveGenericObjects : ICollectionGenericObjects yield return _collection[i]; } } + + public void CollectionSort(IComparer comparer) + { + if (_collection?.Length > 0) + { + Array.Sort(_collection, comparer); + Array.Reverse(_collection); + } + } + } diff --git a/ProjectElectricLocomotive/ProjectElectricLocomotive/CollectionGenericObjects/StorageCollection.cs b/ProjectElectricLocomotive/ProjectElectricLocomotive/CollectionGenericObjects/StorageCollection.cs index b9d1c06..a0429c3 100644 --- a/ProjectElectricLocomotive/ProjectElectricLocomotive/CollectionGenericObjects/StorageCollection.cs +++ b/ProjectElectricLocomotive/ProjectElectricLocomotive/CollectionGenericObjects/StorageCollection.cs @@ -18,12 +18,12 @@ public class StorageCollection /// /// Словарь с коллекциями /// - readonly Dictionary> _storages; + readonly Dictionary> _storages; /// /// Возвращение списка названий коллекций /// - public List Keys => _storages.Keys.ToList(); + public List Keys => _storages.Keys.ToList(); /// /// Ключевое слово, с которого должен начинаться файл @@ -45,7 +45,7 @@ public class StorageCollection /// public StorageCollection() { - _storages = new Dictionary>(); + _storages = new Dictionary>(); } /// @@ -57,14 +57,15 @@ public class StorageCollection { // проверка что name не пустой и нет в словаре записи с таким ключом // логика добавления - if (string.IsNullOrEmpty(name) || _storages.ContainsKey(name) || collectionType == CollectionType.None) return; + CollectionInfo collectionInfo = new(name, collectionType, string.Empty); + if (string.IsNullOrEmpty(collectionInfo.Name) || _storages.ContainsKey(collectionInfo)) return; if (collectionType == CollectionType.Massive) { - _storages[name] = new MassiveGenericObjects(); + _storages[collectionInfo] = new MassiveGenericObjects(); } else if (collectionType == CollectionType.List) { - _storages[name] = new ListGenericObjects(); + _storages[collectionInfo] = new ListGenericObjects(); } } @@ -75,10 +76,9 @@ public class StorageCollection /// Имя коллекции public void DelCollection(string name) { - if (_storages.ContainsKey(name)) - { - _storages.Remove(name); - } + var obj = new CollectionInfo(name, CollectionType.None, string.Empty); + if (!_storages.ContainsKey(obj)) return; + _storages.Remove(obj); } public ICollectionGenericObjects? this[int index] @@ -113,9 +113,9 @@ public class StorageCollection using (StreamWriter writer = new StreamWriter(filename)) { writer.WriteLine(_collectionKey); - foreach (KeyValuePair> value in _storages) + foreach (KeyValuePair> value in _storages) { - writer.Write($"{value.Key}{_separatorForKeyValue}{value.Value.GetCollectionType}{_separatorForKeyValue}{value.Value.MaxCount}{_separatorForKeyValue}"); + writer.Write($"{value.Key}{_separatorForKeyValue}{value.Value.MaxCount}{_separatorForKeyValue}"); writer.Write(_separatorItems); foreach (T? item in value.Value.GetItems()) @@ -158,21 +158,22 @@ public class StorageCollection { string[] record = line.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); - if (record.Length != 4) + if (record.Length != 3) { line = reader.ReadLine(); continue; } - CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]); + CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(record[0]) ?? + throw new Exception("Не удалось определить информацию коллекции: " + record[0]); - ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType); + ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionInfo.CollectionType); if (collection == null) throw new NullCollectionExpection("Не удалось создать коллекцию"); ; - 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) { @@ -180,7 +181,7 @@ public class StorageCollection { try { - collection.Insert(locomotive); + collection.Insert(locomotive, new DrawningLocomotiveEqutables()); } catch(Exception ex) { @@ -188,7 +189,7 @@ public class StorageCollection } } } - _storages.Add(record[0], collection); + _storages.Add(collectionInfo, collection); line = reader.ReadLine(); } diff --git a/ProjectElectricLocomotive/ProjectElectricLocomotive/Drawnings/DrawningLocomotiveCompareByColor.cs b/ProjectElectricLocomotive/ProjectElectricLocomotive/Drawnings/DrawningLocomotiveCompareByColor.cs new file mode 100644 index 0000000..e62cbd0 --- /dev/null +++ b/ProjectElectricLocomotive/ProjectElectricLocomotive/Drawnings/DrawningLocomotiveCompareByColor.cs @@ -0,0 +1,45 @@ +using ProjectElectricLocomotive.Entities; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectElectricLocomotive.Drawnings; + +/// +/// Сравнение по цвету, скорости, весу +/// +public class DrawningLocomotiveCompareByColor : IComparer +{ + public int Compare(DrawningLocomotive? x, DrawningLocomotive? y) + { + if (x == null && y == null) return 0; + if (x == null || x.EntityLocomotive == null) return -1; + if (y == null || y.EntityLocomotive == null) return 1; + if (x.GetType().Name != y.GetType().Name) return -1; + + var colorCompare = x.EntityLocomotive.BodyColor.ToArgb().CompareTo(y.EntityLocomotive.BodyColor.ToArgb()); + if (colorCompare != 0) + { + return colorCompare; + } + + if (x is DrawningElectricLocomotive && y is DrawningElectricLocomotive) + { + colorCompare = ((EntityElectricLocomotive)x.EntityLocomotive).AdditionalColor.ToArgb().CompareTo(((EntityElectricLocomotive)y.EntityLocomotive).AdditionalColor.ToArgb()); + if (colorCompare != 0) + { + return colorCompare; + } + } + + var speedCompare = x.EntityLocomotive.Speed.CompareTo(y.EntityLocomotive.Speed); + if (speedCompare != 0) + { + return speedCompare; + } + + return x.EntityLocomotive.Weight.CompareTo(y.EntityLocomotive.Weight); + } +} diff --git a/ProjectElectricLocomotive/ProjectElectricLocomotive/Drawnings/DrawningLocomotiveCompareByType.cs b/ProjectElectricLocomotive/ProjectElectricLocomotive/Drawnings/DrawningLocomotiveCompareByType.cs new file mode 100644 index 0000000..031c4e8 --- /dev/null +++ b/ProjectElectricLocomotive/ProjectElectricLocomotive/Drawnings/DrawningLocomotiveCompareByType.cs @@ -0,0 +1,31 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectElectricLocomotive.Drawnings; + +/// +/// Сравнение по типу, скорости, весу +/// +public class DrawningLocomotiveCompareByType : IComparer +{ + public int Compare(DrawningLocomotive? x, DrawningLocomotive? y) + { + if (x == null && y == null) return 0; + if (x == null || x.EntityLocomotive == null) return -1; + if (y == null || y.EntityLocomotive == null) return 1; + if (x.GetType().Name != y.GetType().Name) + { + return x.GetType().Name.CompareTo(y.GetType().Name); + } + var speedCompare = x.EntityLocomotive.Speed.CompareTo(y.EntityLocomotive.Speed); + if (speedCompare != 0) + { + return speedCompare; + } + return x.EntityLocomotive.Weight.CompareTo(y.EntityLocomotive.Weight); + + } +} diff --git a/ProjectElectricLocomotive/ProjectElectricLocomotive/Drawnings/DrawningLocomotiveEqutables.cs b/ProjectElectricLocomotive/ProjectElectricLocomotive/Drawnings/DrawningLocomotiveEqutables.cs new file mode 100644 index 0000000..ec5e662 --- /dev/null +++ b/ProjectElectricLocomotive/ProjectElectricLocomotive/Drawnings/DrawningLocomotiveEqutables.cs @@ -0,0 +1,34 @@ +using ProjectElectricLocomotive.Entities; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectElectricLocomotive.Drawnings; + +public class DrawningLocomotiveEqutables : IEqualityComparer +{ + public bool Equals(DrawningLocomotive? x, DrawningLocomotive? y) + { + if (x == null || x.EntityLocomotive == null) return false; + if (y == null || y.EntityLocomotive == null) return false; + if (x.GetType().Name != y.GetType().Name) return false; + if (x.EntityLocomotive.Speed != y.EntityLocomotive.Speed) return false; + if (x.EntityLocomotive.Weight != y.EntityLocomotive.Weight) return false; + if (x.EntityLocomotive.BodyColor != y.EntityLocomotive.BodyColor) return false; + if (x is DrawningElectricLocomotive && y is DrawningElectricLocomotive) + { + if (((EntityElectricLocomotive)x.EntityLocomotive).AdditionalColor != ((EntityElectricLocomotive)y.EntityLocomotive).AdditionalColor) return false; + if (((EntityElectricLocomotive)x.EntityLocomotive).ElectricHorns != ((EntityElectricLocomotive)y.EntityLocomotive).ElectricHorns) return false; + if (((EntityElectricLocomotive)x.EntityLocomotive).BatteryPlacement != ((EntityElectricLocomotive)y.EntityLocomotive).BatteryPlacement) return false; + } + return true; + } + + public int GetHashCode([DisallowNull] DrawningLocomotive obj) + { + return obj.GetHashCode(); + } +} diff --git a/ProjectElectricLocomotive/ProjectElectricLocomotive/Exceptions/AlreadyExistingObject.cs b/ProjectElectricLocomotive/ProjectElectricLocomotive/Exceptions/AlreadyExistingObject.cs new file mode 100644 index 0000000..8229aa3 --- /dev/null +++ b/ProjectElectricLocomotive/ProjectElectricLocomotive/Exceptions/AlreadyExistingObject.cs @@ -0,0 +1,23 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectElectricLocomotive.Exceptions; + +/// +/// Класс, описывающий переполнение коллекции +/// +[Serializable] +internal class AlreadyExistingObject : ApplicationException +{ + public AlreadyExistingObject(string objName) : base("Данный объект уже существует " + objName) { } + + public AlreadyExistingObject() : base() { } + + public AlreadyExistingObject(string message, Exception exception) : base(message, exception) { } + + public AlreadyExistingObject(SerializationInfo info, StreamingContext context) : base(info, context) { } +} diff --git a/ProjectElectricLocomotive/ProjectElectricLocomotive/FormLocomotiveCollection.Designer.cs b/ProjectElectricLocomotive/ProjectElectricLocomotive/FormLocomotiveCollection.Designer.cs index 85e6d7b..50d9d0f 100644 --- a/ProjectElectricLocomotive/ProjectElectricLocomotive/FormLocomotiveCollection.Designer.cs +++ b/ProjectElectricLocomotive/ProjectElectricLocomotive/FormLocomotiveCollection.Designer.cs @@ -53,6 +53,8 @@ loadToolStripMenuItem = new ToolStripMenuItem(); saveFileDialog = new SaveFileDialog(); openFileDialog = new OpenFileDialog(); + buttonSortByColor = new Button(); + buttonSortByType = new Button(); groupBoxTools.SuspendLayout(); panelCompanyTools.SuspendLayout(); panelStorage.SuspendLayout(); @@ -69,7 +71,7 @@ groupBoxTools.Dock = DockStyle.Right; groupBoxTools.Location = new Point(640, 24); groupBoxTools.Name = "groupBoxTools"; - groupBoxTools.Size = new Size(200, 569); + groupBoxTools.Size = new Size(200, 678); groupBoxTools.TabIndex = 0; groupBoxTools.TabStop = false; groupBoxTools.Text = "Инструменты"; @@ -98,6 +100,8 @@ // // panelCompanyTools // + panelCompanyTools.Controls.Add(buttonSortByColor); + panelCompanyTools.Controls.Add(buttonSortByType); panelCompanyTools.Controls.Add(buttonAddLocomotive); panelCompanyTools.Controls.Add(buttonRefresh); panelCompanyTools.Controls.Add(maskedTextBoxPosition); @@ -105,9 +109,9 @@ panelCompanyTools.Controls.Add(buttonRemoveLocomotive); panelCompanyTools.Dock = DockStyle.Bottom; panelCompanyTools.Enabled = false; - panelCompanyTools.Location = new Point(3, 340); + panelCompanyTools.Location = new Point(3, 364); panelCompanyTools.Name = "panelCompanyTools"; - panelCompanyTools.Size = new Size(194, 226); + panelCompanyTools.Size = new Size(194, 311); panelCompanyTools.TabIndex = 8; // // buttonAddLocomotive @@ -246,7 +250,7 @@ pictureBox.Dock = DockStyle.Fill; pictureBox.Location = new Point(0, 24); pictureBox.Name = "pictureBox"; - pictureBox.Size = new Size(640, 569); + pictureBox.Size = new Size(640, 678); pictureBox.TabIndex = 1; pictureBox.TabStop = false; // @@ -290,11 +294,31 @@ // openFileDialog.Filter = "txt file|*.txt"; // + // buttonSortByColor + // + buttonSortByColor.Location = new Point(3, 260); + buttonSortByColor.Name = "buttonSortByColor"; + buttonSortByColor.Size = new Size(188, 31); + buttonSortByColor.TabIndex = 8; + buttonSortByColor.Text = "Сортировка по цвету"; + buttonSortByColor.UseVisualStyleBackColor = true; + buttonSortByColor.Click += ButtonSortByColor_Click; + // + // buttonSortByType + // + buttonSortByType.Location = new Point(3, 223); + buttonSortByType.Name = "buttonSortByType"; + buttonSortByType.Size = new Size(188, 31); + buttonSortByType.TabIndex = 7; + buttonSortByType.Text = "Сортировка по типу"; + buttonSortByType.UseVisualStyleBackColor = true; + buttonSortByType.Click += ButtonSortByType_Click; + // // FormLocomotiveCollection // AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(840, 593); + ClientSize = new Size(840, 702); Controls.Add(pictureBox); Controls.Add(groupBoxTools); Controls.Add(menuStrip); @@ -340,5 +364,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/ProjectElectricLocomotive/ProjectElectricLocomotive/FormLocomotiveCollection.cs b/ProjectElectricLocomotive/ProjectElectricLocomotive/FormLocomotiveCollection.cs index 5fc3458..392d5d6 100644 --- a/ProjectElectricLocomotive/ProjectElectricLocomotive/FormLocomotiveCollection.cs +++ b/ProjectElectricLocomotive/ProjectElectricLocomotive/FormLocomotiveCollection.cs @@ -78,19 +78,19 @@ public partial class FormLocomotiveCollection : Form try { - if((_company + locomotive) != -1) + if ((_company + locomotive) != -1) { MessageBox.Show("Объект добавлен"); _logger.LogInformation("Добавлен объект: {entity}", locomotive.GetDataForSave()); pictureBox.Image = _company.Show(); } } - catch(Exception ex) + catch (Exception ex) { MessageBox.Show("Объект не был добавлен"); _logger.LogError("Ошибка: {Message}", ex.Message); } - + } @@ -228,11 +228,11 @@ public partial class FormLocomotiveCollection : Form private void RefreshListBoxItems() { listBoxCollection.Items.Clear(); - foreach(string colName in _storageCollection.Keys) + foreach (var colName in _storageCollection.Keys) { - if (!string.IsNullOrEmpty(colName)) + if (!string.IsNullOrEmpty(colName.Name)) { - listBoxCollection.Items.Add(colName); + listBoxCollection.Items.Add(colName.Name); } } } @@ -284,7 +284,7 @@ public partial class FormLocomotiveCollection : Form MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); _logger.LogInformation("Сохранение в файл {filename}", saveFileDialog.FileName); } - catch (Exception ex) + catch (Exception ex) { MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); _logger.LogError("Ошибка {Message}", ex.Message); @@ -307,7 +307,7 @@ public partial class FormLocomotiveCollection : Form MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); _logger.LogInformation("Загрузка прошла успешно из файла, {filename}", openFileDialog.FileName); } - catch(Exception ex) + catch (Exception ex) { MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); _logger.LogError("Ошибка {Message}", ex.Message); @@ -315,4 +315,36 @@ public partial class FormLocomotiveCollection : Form RefreshListBoxItems(); } } + + /// + /// Сортировка по типу + /// + /// + /// + private void ButtonSortByType_Click(object sender, EventArgs e) + { + CompareCars(new DrawningLocomotiveCompareByType()); + } + + /// + /// Сортировка по цвету + /// + /// + /// + private void ButtonSortByColor_Click(object sender, EventArgs e) + { + CompareCars(new DrawningLocomotiveCompareByColor()); + } + + /// + /// Сортировка по сравнителю + /// + /// Сравнитель объектов + private void CompareCars(IComparer comparer) + { + if (_company == null) return; + + _company.Sort(comparer); + pictureBox.Image = _company.Show(); + } }