diff --git a/ProjectSportCar/ProjectSportCar/CollectionGenericObjects/AbstractCompany.cs b/ProjectSportCar/ProjectSportCar/CollectionGenericObjects/AbstractCompany.cs index 1406305..a8a7d76 100644 --- a/ProjectSportCar/ProjectSportCar/CollectionGenericObjects/AbstractCompany.cs +++ b/ProjectSportCar/ProjectSportCar/CollectionGenericObjects/AbstractCompany.cs @@ -63,7 +63,7 @@ public abstract class AbstractCompany /// public static int operator +(AbstractCompany company, DrawingWarship warship) { - return company._collection.Insert(warship); + return company._collection.Insert(warship, new DrawingWarshipEqutables()); } /// /// Перезагрузка оператора удаления для класса @@ -105,6 +105,12 @@ public abstract class AbstractCompany return bitmap; } + /// + /// Сортировка + /// + /// + public void Sort(IComparer comparer) => _collection?.CollectionSort(comparer); + /// /// Вывод заднего фона /// diff --git a/ProjectSportCar/ProjectSportCar/CollectionGenericObjects/CollectionInfo.cs b/ProjectSportCar/ProjectSportCar/CollectionGenericObjects/CollectionInfo.cs new file mode 100644 index 0000000..cada9a6 --- /dev/null +++ b/ProjectSportCar/ProjectSportCar/CollectionGenericObjects/CollectionInfo.cs @@ -0,0 +1,77 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectLinkor.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; + } + + 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/ProjectSportCar/ProjectSportCar/CollectionGenericObjects/ICollectionGenericObjects.cs b/ProjectSportCar/ProjectSportCar/CollectionGenericObjects/ICollectionGenericObjects.cs index d81d917..ede9f90 100644 --- a/ProjectSportCar/ProjectSportCar/CollectionGenericObjects/ICollectionGenericObjects.cs +++ b/ProjectSportCar/ProjectSportCar/CollectionGenericObjects/ICollectionGenericObjects.cs @@ -22,16 +22,18 @@ 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); /// /// Удаление объекта из коллекции с конкретной позиции @@ -57,4 +59,10 @@ public interface ICollectionGenericObjects /// /// IEnumerable GetItems(); + + /// + /// Сортировка коллекции + /// + /// + void CollectionSort(IComparer comparer); } diff --git a/ProjectSportCar/ProjectSportCar/CollectionGenericObjects/ListGenericObjects.cs b/ProjectSportCar/ProjectSportCar/CollectionGenericObjects/ListGenericObjects.cs index 9d50884..f73355f 100644 --- a/ProjectSportCar/ProjectSportCar/CollectionGenericObjects/ListGenericObjects.cs +++ b/ProjectSportCar/ProjectSportCar/CollectionGenericObjects/ListGenericObjects.cs @@ -54,41 +54,41 @@ public class ListGenericObjects : ICollectionGenericObjects return _collection[position]; } - public int Insert(T obj) + public int Insert(T obj, IEqualityComparer? comparer = null) { - // проверка, что не превышено максимальное количество элементов - if (_collection.Count >= _maxCount) + if (comparer != null) { - throw new CollectionOverflowException(_maxCount); + if (_collection.Contains(obj, comparer)) + { + throw new ObjectIsEqualException(); + } } - // вставка в конец набора + if (Count == _maxCount) throw new CollectionOverflowException(); _collection.Add(obj); - return _maxCount; + 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(_maxCount); - - // проверка позиции - if (position < 0 || position >= _maxCount) - throw new PositionOutOfCollectionException(position); - - // вставка по позиции + if (comparer != null) + { + if (_collection.Contains(obj, comparer)) + { + throw new ObjectIsEqualException(); + } + } + if (Count == _maxCount) throw new CollectionOverflowException(Count); + if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position); _collection.Insert(position, obj); return position; } public T Remove(int position) { - // проверка позиции - if (position < 0 || position > _maxCount) throw new PositionOutOfCollectionException(position); - // удаление объекта из списка - T temp = _collection[position]; - _collection[position] = null; - return temp; + if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position); + T obj = _collection[position]; + _collection.RemoveAt(position); + return obj; } public IEnumerable GetItems() @@ -98,4 +98,9 @@ public class ListGenericObjects : ICollectionGenericObjects yield return _collection[i]; } } + + public void CollectionSort(IComparer comparer) + { + _collection.Sort(comparer); + } } diff --git a/ProjectSportCar/ProjectSportCar/CollectionGenericObjects/MassiveGenericObjects.cs b/ProjectSportCar/ProjectSportCar/CollectionGenericObjects/MassiveGenericObjects.cs index 93dc425..bd245a9 100644 --- a/ProjectSportCar/ProjectSportCar/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/ProjectSportCar/ProjectSportCar/CollectionGenericObjects/MassiveGenericObjects.cs @@ -1,4 +1,5 @@ using ProjectLinkor.CollectionGenericObjects; +using ProjectLinkor.Drawnings; using ProjectLinkor.Exceptions; namespace ProjectLinkor.CollectionGenericObjects; @@ -59,9 +60,16 @@ public class MassiveGenericObjects : ICollectionGenericObjects return _collection[position]; } - public int Insert(T obj) + public int Insert(T obj, IEqualityComparer? comparer = null) { - // TODO вставка в свободное место набора + if (comparer != null) + { + foreach (T? item in _collection) + { + if ((comparer as IEqualityComparer).Equals(obj as DrawingWarship, item as DrawingWarship)) + throw new ObjectIsEqualException(); + } + } int index = 0; while (index < _collection.Length) { @@ -70,64 +78,61 @@ public class MassiveGenericObjects : ICollectionGenericObjects _collection[index] = obj; return index; } + index++; } throw new CollectionOverflowException(Count); } - public int Insert(T obj, int position) + public int Insert(T obj, int position, IEqualityComparer? comparer = null) { - // проверка позиции - if (position >= _collection.Length || position < 0) - throw new PositionOutOfCollectionException(position); - - // проверка, что элемент массива по этой позиции пустой, если нет, то - if (_collection[position] != null) + if (comparer != null) { - // проверка, что после вставляемого элемента в массиве есть пустой элемент - int nullIndex = -1; - for (int i = position + 1; i < Count; i++) + foreach (T? item in _collection) { - if (_collection[i] == null) - { - nullIndex = i; - break; - } + if ((comparer as IEqualityComparer).Equals(obj as DrawingWarship, item as DrawingWarship)) + throw new ObjectIsEqualException(); } - // Если пустого элемента нет, то выходим - if (nullIndex < 0) - { - return -1; - } - // сдвиг всех объектов, находящихся справа от позиции до первого пустого элемента - int j = nullIndex - 1; - while (j >= position) - { - _collection[j + 1] = _collection[j]; - j--; - } - throw new CollectionOverflowException(Count); } - // вставка по позиции - _collection[position] = obj; - return position; + if (position >= _collection.Length || position < 0) + { + throw new PositionOutOfCollectionException(position); + } + + if (_collection[position] == null) + { + _collection[position] = obj; + return position; + } + int index; + + for (index = position + 1; index < _collection.Length; ++index) + { + if (_collection[index] == null) + { + _collection[position] = obj; + return position; + } + } + + for (index = position - 1; index >= 0; --index) + { + if (_collection[index] == null) + { + _collection[position] = obj; + return position; + } + } + throw new CollectionOverflowException(Count); } public T? Remove(int position) { - // проверка позиции - // удаление объекта из массива, присвоив элементу массива значение null - if (position >= _collection.Length || position < 0) - { - throw new PositionOutOfCollectionException(position); - } - if (_collection[position] == null) - { - throw new ObjectNotFoundException(position); - } - T temp = _collection[position]; + if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position); + if (_collection[position] == null) throw new ObjectNotFoundException(position); + T obj = _collection[position]; _collection[position] = null; - return temp; + return obj; } public IEnumerable GetItems() @@ -137,4 +142,9 @@ public class MassiveGenericObjects : ICollectionGenericObjects yield return _collection[i]; } } + + public void CollectionSort(IComparer comparer) + { + Array.Sort(_collection, comparer); + } } diff --git a/ProjectSportCar/ProjectSportCar/CollectionGenericObjects/StorageCollection.cs b/ProjectSportCar/ProjectSportCar/CollectionGenericObjects/StorageCollection.cs index bb67d6c..ca1b3be 100644 --- a/ProjectSportCar/ProjectSportCar/CollectionGenericObjects/StorageCollection.cs +++ b/ProjectSportCar/ProjectSportCar/CollectionGenericObjects/StorageCollection.cs @@ -1,5 +1,6 @@ using ProjectLinkor.Drawnings; using ProjectLinkor.Exceptions; +using System.Collections.Generic; using System.Text; namespace ProjectLinkor.CollectionGenericObjects; @@ -14,27 +15,36 @@ public class StorageCollection /// /// Словарь (хранилище) с коллекциями /// - private Dictionary> _storages; + readonly Dictionary> _storages; /// /// Возвращение списка названий коллекции /// - public List Keys => _storages.Keys.ToList(); + public List Keys => _storages.Keys.ToList(); + + /// + /// Ключевое слово, с которого должен начинаться файл + /// + private readonly string _collectionKey = "CollectionStorage"; + + /// + /// Разделитель для записи ключа и значения элемента словаря + /// + private readonly string _separatorForKeyValue = "|"; + + /// + /// Разделитель для записей коллекции данных в файл + /// + private readonly string _separatorItems = ";"; /// /// Конструктор /// public StorageCollection() { - _storages = new Dictionary>(); + _storages = new Dictionary>(); } - private readonly string _collectionKey = "CollectionsStorage"; - - private readonly string _separatorForKeyValue = "|"; - - private readonly string _separatorItems = ";"; - /// /// Добавление коллекции в хранилище /// @@ -42,18 +52,20 @@ public class StorageCollection /// Тип коллекции public void AddCollection(string name, CollectionType collectionType) { - if (string.IsNullOrEmpty(name) || _storages.ContainsKey(name)) + // проверка, что name не пустой и нет в словаре записи с таким ключом + if (string.IsNullOrEmpty(name) || _storages.ContainsKey(new CollectionInfo(name, collectionType, string.Empty))) { + MessageBox.Show("Коллекция с таким именем уже существует", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } - // TODO Прописать логику для добавления + // прописать логику для добавления if (collectionType == CollectionType.List) { - _storages.Add(name, new ListGenericObjects()); + _storages.Add(new CollectionInfo(name, collectionType, string.Empty), new ListGenericObjects()); } if (collectionType == CollectionType.Massive) { - _storages.Add(name, new MassiveGenericObjects()); + _storages.Add(new CollectionInfo(name, collectionType, string.Empty), new MassiveGenericObjects()); } } @@ -63,10 +75,9 @@ public class StorageCollection /// public void DelCollection(string name) { - // TODO Прописать логику для удаления коллекции - if (!_storages.ContainsKey(name)) - return; - _storages.Remove(name); + // прописать логику для удаления коллекции + if (!_storages.ContainsKey(new CollectionInfo(name, CollectionType.None, string.Empty))) return; + _storages.Remove(new CollectionInfo(name, CollectionType.None, string.Empty)); } /// @@ -78,10 +89,10 @@ public class StorageCollection { get { - // TODO Продумать логику получения объекта - if (_storages.ContainsKey((string)name)) + // продумать логику получения объекта + if (_storages.ContainsKey(new CollectionInfo(name, CollectionType.None, string.Empty))) { - return _storages[name]; + return _storages[new CollectionInfo(name, CollectionType.None, string.Empty)]; } return null; } @@ -107,7 +118,7 @@ public class StorageCollection using (StreamWriter writer = new StreamWriter(filename)) { writer.Write(_collectionKey); - foreach (KeyValuePair> value in _storages) + foreach (KeyValuePair> value in _storages) { writer.Write(Environment.NewLine); // не сохраняем пустые коллекции @@ -118,8 +129,6 @@ public class StorageCollection writer.Write(value.Key); writer.Write(_separatorForKeyValue); - writer.Write(value.Value.GetCollectionType); - writer.Write(_separatorForKeyValue); writer.Write(value.Value.MaxCount); writer.Write(_separatorForKeyValue); @@ -161,7 +170,6 @@ public class StorageCollection if (!str.StartsWith(_collectionKey)) { - //если нет такой записи, то это не те данные throw new Exception("В файле неверные данные"); } @@ -170,21 +178,23 @@ public class StorageCollection while ((strs = reader.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); + CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(record[0]) ?? + throw new Exception("Не удалось определить информацию коллекции" + record[0]); + ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionInfo.CollectionType) ?? + throw new Exception("Не удалось создать коллекцию"); if (collection == null) { throw new Exception("Не удалось создать коллекцию"); } - collection.MaxCount = Convert.ToInt32(record[2]); + collection.MaxCount = Convert.ToInt32(record[1]); - string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); + string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); foreach (string elem in set) { if (elem?.CreateDrawingWarship() is T bulldozer) @@ -203,7 +213,7 @@ public class StorageCollection } } - _storages.Add(record[0], collection); + _storages.Add(collectionInfo, collection); } } } diff --git a/ProjectSportCar/ProjectSportCar/Drawnings/DrawingWarshipCompareByType.cs b/ProjectSportCar/ProjectSportCar/Drawnings/DrawingWarshipCompareByType.cs new file mode 100644 index 0000000..cb592cb --- /dev/null +++ b/ProjectSportCar/ProjectSportCar/Drawnings/DrawingWarshipCompareByType.cs @@ -0,0 +1,40 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectLinkor.Drawnings; + +/// +/// Сравнение по типу, скорости, весу +/// +internal class DrawingWarshipCompareByType : IComparer +{ + public int Compare(DrawingWarship? x, DrawingWarship? y) + { + if (x == null || x.EntityWarship == null) + { + return 1; + } + + if (y == null || y.EntityWarship == null) + { + return -1; + } + + if (x.GetType().Name != y.GetType().Name) + { + return x.GetType().Name.CompareTo(y.GetType().Name); + } + + var speedCompare = x.EntityWarship.Speed.CompareTo(y.EntityWarship.Speed); + + if (speedCompare != 0) + { + return speedCompare; + } + + return x.EntityWarship.Weight.CompareTo(y.EntityWarship.Weight); + } +} diff --git a/ProjectSportCar/ProjectSportCar/Drawnings/DrawingWarshipComparerByColor.cs b/ProjectSportCar/ProjectSportCar/Drawnings/DrawingWarshipComparerByColor.cs new file mode 100644 index 0000000..ea65614 --- /dev/null +++ b/ProjectSportCar/ProjectSportCar/Drawnings/DrawingWarshipComparerByColor.cs @@ -0,0 +1,41 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectLinkor.Drawnings; + +/// +/// Сравнение по цвету, скорости, весу +/// +public class DrawingWarshipComparerByColor : IComparer +{ + public int Compare(DrawingWarship? x, DrawingWarship? y) + { + // TODO прописать логику сравнения по цветам, скорости, весу + if (x == null || x.EntityWarship == null) + { + return 1; + } + + if (y == null || y.EntityWarship == null) + { + return -1; + } + + if (x.EntityWarship.BodyColor != y.EntityWarship.BodyColor) + { + return x.EntityWarship.BodyColor.Name.CompareTo(y.EntityWarship.BodyColor.Name); + } + + var speedCompare = x.EntityWarship.Speed.CompareTo(y.EntityWarship.Speed); + + if (speedCompare != 0) + { + return speedCompare; + } + + return x.EntityWarship.Weight.CompareTo(y.EntityWarship.Weight); + } +} diff --git a/ProjectSportCar/ProjectSportCar/Drawnings/DrawingWarshipEqutables.cs b/ProjectSportCar/ProjectSportCar/Drawnings/DrawingWarshipEqutables.cs new file mode 100644 index 0000000..b980a5e --- /dev/null +++ b/ProjectSportCar/ProjectSportCar/Drawnings/DrawingWarshipEqutables.cs @@ -0,0 +1,71 @@ +using ProjectLinkor.Entities; +using System.Diagnostics.CodeAnalysis; + +namespace ProjectLinkor.Drawnings; + +/// +/// Реализация сравнения двух объектов класса-прорисовки +/// +public class DrawingWarshipEqutables : IEqualityComparer +{ + public bool Equals(DrawingWarship? x, DrawingWarship? y) + { + if (x == null || x.EntityWarship == null) + { + return false; + } + + if (y == null || y.EntityWarship == null) + { + return false; + } + + if (x.GetType().Name != y.GetType().Name) + { + return false; + } + + if (x.EntityWarship.Speed != y.EntityWarship.Speed) + { + return false; + } + + if (x.EntityWarship.Weight != y.EntityWarship.Weight) + { + return false; + } + if (x.EntityWarship.BodyColor != y.EntityWarship.BodyColor) + { + return false; + } + + if (x is DrawningLinkor && y is DrawningLinkor) + { + // TODO доделать логику сравнения дополнительных параметров + EntityLinkor xLinkor = (EntityLinkor)x.EntityWarship; + EntityLinkor yLinkor = (EntityLinkor)y.EntityWarship; + + if (xLinkor.AdditionalColor != yLinkor.AdditionalColor) + { + return false; + } + + if (xLinkor.Сompartment != yLinkor.Сompartment) + { + return false; + } + + if (xLinkor.GunTurret != yLinkor.GunTurret) + { + return false; + } + } + + return true; + } + + public int GetHashCode([DisallowNull] DrawingWarship obj) + { + return obj.GetHashCode(); + } +} diff --git a/ProjectSportCar/ProjectSportCar/Exceptions/ObjectIsEqualException.cs b/ProjectSportCar/ProjectSportCar/Exceptions/ObjectIsEqualException.cs new file mode 100644 index 0000000..3d0fd47 --- /dev/null +++ b/ProjectSportCar/ProjectSportCar/Exceptions/ObjectIsEqualException.cs @@ -0,0 +1,16 @@ +using System.Runtime.Serialization; + +namespace ProjectLinkor.Exceptions; + +/// +/// Класс, описывающий ошибку переполнения коллекции +/// +[Serializable] +public class ObjectIsEqualException : ApplicationException +{ + public ObjectIsEqualException(int count) : base("В коллекции содержится равный элемент: " + count) { } + public ObjectIsEqualException() : base() { } + public ObjectIsEqualException(string message) : base(message) { } + public ObjectIsEqualException(string message, Exception exception) : base(message, exception) { } + protected ObjectIsEqualException(SerializationInfo info, StreamingContext contex) : base(info, contex) { } +} diff --git a/ProjectSportCar/ProjectSportCar/FormWarshipCollection.Designer.cs b/ProjectSportCar/ProjectSportCar/FormWarshipCollection.Designer.cs index 1e4cba5..0e11207 100644 --- a/ProjectSportCar/ProjectSportCar/FormWarshipCollection.Designer.cs +++ b/ProjectSportCar/ProjectSportCar/FormWarshipCollection.Designer.cs @@ -52,6 +52,8 @@ loadToolStripMenuItem = new ToolStripMenuItem(); saveFileDialog = new SaveFileDialog(); openFileDialog = new OpenFileDialog(); + buttonSortByType = new Button(); + buttonSortByColor = new Button(); groupBoxTools.SuspendLayout(); panelCompanyTools.SuspendLayout(); panelStorage.SuspendLayout(); @@ -75,6 +77,8 @@ // // panelCompanyTools // + panelCompanyTools.Controls.Add(buttonSortByColor); + panelCompanyTools.Controls.Add(buttonSortByType); panelCompanyTools.Controls.Add(buttonAddWarship); panelCompanyTools.Controls.Add(maskedTextBox1); panelCompanyTools.Controls.Add(buttonRemoveWarship); @@ -82,15 +86,15 @@ panelCompanyTools.Controls.Add(buttonGoToCheck); panelCompanyTools.Dock = DockStyle.Bottom; panelCompanyTools.Enabled = false; - panelCompanyTools.Location = new Point(3, 384); + panelCompanyTools.Location = new Point(3, 374); panelCompanyTools.Name = "panelCompanyTools"; - panelCompanyTools.Size = new Size(286, 291); + panelCompanyTools.Size = new Size(286, 301); panelCompanyTools.TabIndex = 9; // // buttonAddWarship // buttonAddWarship.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonAddWarship.Location = new Point(3, 16); + buttonAddWarship.Location = new Point(3, 3); buttonAddWarship.Name = "buttonAddWarship"; buttonAddWarship.Size = new Size(271, 33); buttonAddWarship.TabIndex = 1; @@ -101,7 +105,7 @@ // maskedTextBox1 // maskedTextBox1.Anchor = AnchorStyles.Left | AnchorStyles.Right; - maskedTextBox1.Location = new Point(3, 81); + maskedTextBox1.Location = new Point(3, 42); maskedTextBox1.Mask = "00"; maskedTextBox1.Name = "maskedTextBox1"; maskedTextBox1.Size = new Size(271, 27); @@ -110,7 +114,7 @@ // buttonRemoveWarship // buttonRemoveWarship.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonRemoveWarship.Location = new Point(3, 124); + buttonRemoveWarship.Location = new Point(3, 75); buttonRemoveWarship.Name = "buttonRemoveWarship"; buttonRemoveWarship.Size = new Size(271, 42); buttonRemoveWarship.TabIndex = 4; @@ -121,7 +125,7 @@ // buttonRefresh // buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonRefresh.Location = new Point(3, 220); + buttonRefresh.Location = new Point(3, 171); buttonRefresh.Name = "buttonRefresh"; buttonRefresh.Size = new Size(271, 30); buttonRefresh.TabIndex = 6; @@ -132,7 +136,7 @@ // buttonGoToCheck // buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonGoToCheck.Location = new Point(3, 172); + buttonGoToCheck.Location = new Point(3, 123); buttonGoToCheck.Name = "buttonGoToCheck"; buttonGoToCheck.Size = new Size(271, 42); buttonGoToCheck.TabIndex = 5; @@ -294,6 +298,28 @@ // openFileDialog.Filter = "txt file | *.txt"; // + // buttonSortByType + // + buttonSortByType.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + buttonSortByType.Location = new Point(3, 207); + buttonSortByType.Name = "buttonSortByType"; + buttonSortByType.Size = new Size(271, 42); + buttonSortByType.TabIndex = 8; + buttonSortByType.Text = "Сортировка по типу"; + buttonSortByType.UseVisualStyleBackColor = true; + buttonSortByType.Click += buttonSortByType_Click; + // + // buttonSortByColor + // + buttonSortByColor.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + buttonSortByColor.Location = new Point(3, 255); + buttonSortByColor.Name = "buttonSortByColor"; + buttonSortByColor.Size = new Size(271, 30); + buttonSortByColor.TabIndex = 9; + buttonSortByColor.Text = "Сортировка по цвету"; + buttonSortByColor.UseVisualStyleBackColor = true; + buttonSortByColor.Click += buttonSortByColor_Click; + // // FormWarshipCollection // AutoScaleDimensions = new SizeF(8F, 20F); @@ -342,5 +368,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/ProjectSportCar/ProjectSportCar/FormWarshipCollection.cs b/ProjectSportCar/ProjectSportCar/FormWarshipCollection.cs index a431dd6..1434558 100644 --- a/ProjectSportCar/ProjectSportCar/FormWarshipCollection.cs +++ b/ProjectSportCar/ProjectSportCar/FormWarshipCollection.cs @@ -105,22 +105,33 @@ public partial class FormWarshipCollection : Form /// private void SetWarship(DrawingWarship warship) { - if (_company == null || warship == null) - { - return; - } try { + if (_company == null || warship == null) + { + return; + } if (_company + warship != -1) { MessageBox.Show("Объект добавлен"); pictureBox.Image = _company.Show(); - _logger.LogInformation("Добавлен объект: {object}", warship.GetDataForSave()); + _logger.LogInformation("Добавлен объект: " + warship.GetDataForSave()); } } + catch (ObjectNotFoundException) { } catch (CollectionOverflowException ex) { - MessageBox.Show(ex.Message); + MessageBox.Show("Не удалось добавить объект1"); + _logger.LogError("Ошибка: {Message}", ex.Message); + } + catch (PositionOutOfCollectionException ex) + { + MessageBox.Show("Выход за границы коллекции"); + _logger.LogError("Ошибка: {Message}", ex.Message); + } + catch (ObjectIsEqualException ex) + { + MessageBox.Show("Не удалось добавить объект"); _logger.LogError("Ошибка: {Message}", ex.Message); } @@ -242,7 +253,7 @@ public partial class FormWarshipCollection : 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); @@ -329,4 +340,51 @@ public partial class FormWarshipCollection : Form } } } + + /// + /// Сортировка по типу + /// + /// + /// + private void buttonSortByType_Click(object sender, EventArgs e) + { + CompareWarship(new DrawingWarshipCompareByType()); + } + + /// + /// Сортировка по цвету + /// + /// + /// + private void buttonSortByColor_Click(object sender, EventArgs e) + { + CompareExcavators(new DrawingWarshipComparerByColor()); + } + + private void CompareExcavators(IComparer comparer) + { + if (_company == null) + { + return; + } + + _company.Sort(comparer); + pictureBox.Image = _company.Show(); + } + + /// + /// Сортировка по сравнителю + /// + /// Сравнитель объектов + private void CompareWarship(IComparer comparer) + { + if (_company == null) + { + return; + } + + _company.Sort(comparer); + pictureBox.Image = _company.Show(); + } + } \ No newline at end of file