diff --git a/ProjectCruiser/CollectionGenericObj/AbstractCompany.cs b/ProjectCruiser/CollectionGenericObj/AbstractCompany.cs index fdd5d80..fdfd45f 100644 --- a/ProjectCruiser/CollectionGenericObj/AbstractCompany.cs +++ b/ProjectCruiser/CollectionGenericObj/AbstractCompany.cs @@ -30,14 +30,19 @@ public abstract class AbstractCompany } // Перегрузка оператора сложения для класса - // [ ! ] insted of bool: public static int operator +(AbstractCompany company, - DrawningBase trasport) => company._collection.Insert(trasport); + DrawningBase trasport) => + company._collection.Insert(trasport, new DrawiningShipEqutables()); // Перегрузка оператора удаления для класса public static DrawningBase operator -(AbstractCompany company, int pos) => company._collection.Remove(pos); + // Сортировка ----------------------------------------------------------- [!] + public void Sort(IComparer comparer) => + _collection?.CollectionSort(comparer); + + // Получение случайного объекта из коллекции public DrawningBase? GetRandomObject() { diff --git a/ProjectCruiser/CollectionGenericObj/ArrayGenObj.cs b/ProjectCruiser/CollectionGenericObj/ArrayGenObj.cs index 475640a..0bfe319 100644 --- a/ProjectCruiser/CollectionGenericObj/ArrayGenObj.cs +++ b/ProjectCruiser/CollectionGenericObj/ArrayGenObj.cs @@ -1,4 +1,5 @@ -using ProjectCruiser.Exceptions; +using ProjectCruiser.DrawningSamples; +using ProjectCruiser.Exceptions; namespace ProjectCruiser.CollectionGenericObj; @@ -46,16 +47,19 @@ public class ArrayGenObj : ICollectionGenObj throw new ObjectNotFoundException(index); return _collection[index]; - - // CollectionOverflowException - // PositionOutOfCollectionException - // ObjectNotFoundException } - public int Insert(T? item) + public int Insert(T? item, IEqualityComparer? cmpr = null) { if (item == null) throw new NullReferenceException("> Inserting item is null"); + else + { + if (cmpr != null && item == cmpr) + { + throw new Exception(); + } + } // выход за границы, курируется CollectionOverflowException if (Count >= _maxCount) throw new CollectionOverflowException(Count); @@ -70,18 +74,23 @@ public class ArrayGenObj : ICollectionGenObj } } return Count; - - // NullReferenceException - // CollectionOverflowException } - public int Insert(T? item, int index) + public int Insert(T? item, int index, IEqualityComparer? cmpr = null) { + if (index < 0 || index >= _maxCount) throw new PositionOutOfCollectionException(index); if (Count >= _maxCount) throw new CollectionOverflowException(Count); if (item == null) throw new NullReferenceException("> Inserting item (at position) is null"); + else + { + if (cmpr != null && item == cmpr) + { + throw new Exception(); + } + } if (_collection[index] == null) { @@ -104,10 +113,6 @@ public class ArrayGenObj : ICollectionGenObj _collection[firstNullIndex] = item; return firstNullIndex; } - - // PositionOutOfCollectionException - // CollectionOverflowException - // NullReferenceException } public T? Remove(int index) @@ -124,9 +129,6 @@ public class ArrayGenObj : ICollectionGenObj if (item == null) throw new ObjectNotFoundException(index); return item; - - // PositionOutOfCollectionException - // ObjectNotFoundException } public IEnumerable GetItems() @@ -136,5 +138,10 @@ public class ArrayGenObj : ICollectionGenObj yield return _collection[i]; } } + + public void CollectionSort(IComparer comparer) + { + Array.Sort(_collection, comparer); + } } diff --git a/ProjectCruiser/CollectionGenericObj/CollectionInfo.cs b/ProjectCruiser/CollectionGenericObj/CollectionInfo.cs new file mode 100644 index 0000000..a330feb --- /dev/null +++ b/ProjectCruiser/CollectionGenericObj/CollectionInfo.cs @@ -0,0 +1,63 @@ +namespace ProjectCruiser.CollectionGenericObj; + +// Класс, хранящиий информацию по коллекции +/// +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) + { + // if (Name != other.Name) return false; >>> + // else if (CollectionType != other.CollectionType) return false; + // else if (Description != other.Description) return false; + + 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/ProjectCruiser/CollectionGenericObj/ICollectionGenObj.cs b/ProjectCruiser/CollectionGenericObj/ICollectionGenObj.cs index 4af2547..ef7d93a 100644 --- a/ProjectCruiser/CollectionGenericObj/ICollectionGenObj.cs +++ b/ProjectCruiser/CollectionGenericObj/ICollectionGenObj.cs @@ -1,4 +1,6 @@ -namespace ProjectCruiser.CollectionGenericObj; +using ProjectCruiser.DrawningSamples; + +namespace ProjectCruiser.CollectionGenericObj; public interface ICollectionGenObj where T : class { @@ -11,8 +13,8 @@ public interface ICollectionGenObj where T : class /// Добавление объекта в коллекцию /// Добавляемый объект /// true - вставка прошла удачно, false - вставка не удалась - int Insert(T obj); - int Insert(T obj, int position); + int Insert(T obj, IEqualityComparer? cmpr = null); + int Insert(T obj, int position, IEqualityComparer? cmpr = null); /// Удаление объекта из коллекции с конкретной позиции /// Позиция @@ -27,4 +29,8 @@ public interface ICollectionGenObj where T : class // Получение объектов коллекции по одному IEnumerable GetItems(); + + // Сортировка коллекции + /// Сравнитель объектов + void CollectionSort(IComparer comparer); } diff --git a/ProjectCruiser/CollectionGenericObj/ListGenObj.cs b/ProjectCruiser/CollectionGenericObj/ListGenObj.cs index 1cb23cf..9c1fb48 100644 --- a/ProjectCruiser/CollectionGenericObj/ListGenObj.cs +++ b/ProjectCruiser/CollectionGenericObj/ListGenObj.cs @@ -1,4 +1,5 @@ -using ProjectCruiser.Exceptions; +using ProjectCruiser.DrawningSamples; +using ProjectCruiser.Exceptions; namespace ProjectCruiser.CollectionGenericObj; @@ -48,10 +49,17 @@ public class ListGenObj : ICollectionGenObj return _collection[position]; } - public int Insert(T? obj) + public int Insert(T? obj, IEqualityComparer? cmpr = null) { if (obj == null) throw new NullReferenceException("> Inserting object is null"); + else + { + if (cmpr != null && obj == cmpr) + { + throw new Exception(); + } + } // выход за границы, курируется CollectionOverflowException if (Count >= _maxCount) throw new CollectionOverflowException(Count); @@ -60,7 +68,7 @@ public class ListGenObj : ICollectionGenObj return Count; } - public int Insert(T? obj, int position) + public int Insert(T? obj, int position, IEqualityComparer? cmpr = null) { if (position < 0 || position >= _maxCount) throw new PositionOutOfCollectionException(position); @@ -68,6 +76,13 @@ public class ListGenObj : ICollectionGenObj if (obj == null) throw new NullReferenceException("> Inserting object (at position) is null"); + else + { + if (cmpr != null && obj == cmpr) + { + throw new Exception(); + } + } _collection.Insert(position, obj); return position; @@ -96,4 +111,9 @@ public class ListGenObj : ICollectionGenObj yield return _collection[i]; } } + + public void CollectionSort(IComparer comparer) + { + _collection.Sort(comparer); + } } diff --git a/ProjectCruiser/CollectionGenericObj/StorageCollection.cs b/ProjectCruiser/CollectionGenericObj/StorageCollection.cs index acc8411..0286d8d 100644 --- a/ProjectCruiser/CollectionGenericObj/StorageCollection.cs +++ b/ProjectCruiser/CollectionGenericObj/StorageCollection.cs @@ -1,56 +1,58 @@ -using System.Security.Cryptography; +using System.CodeDom; using System.Text; using ProjectCruiser.DrawningSamples; -using ProjectCruiser.Exceptions; namespace ProjectCruiser.CollectionGenericObj; public class StorageCollection where T : DrawningBase // class { - // Разделитель для записи ключа и значения элемента словаря private readonly string _separatorForKeyValue = "|"; - // Разделитель для записей коллекции данных в файл private readonly string _separatorItems = ";"; - - // Ключевое слово, с которого должен начинаться файл private readonly string _collectionKey = "CollectionsStorage"; - // Словарь (хранилище) с коллекциями < name, type (class) > - readonly Dictionary> _storages; + // Словарь (хранилище) с коллекциями < CollectionInfo, type (class) > + 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 collType) { - if (name == null || _storages.ContainsKey(name) + // descroption [ ? ] >>> + CollectionInfo coll = new CollectionInfo(name, collType, string.Empty); + + if (name == null || _storages.ContainsKey(coll) || collType == CollectionType.None) { throw new NullReferenceException("> Not enough information to save"); } - ICollectionGenObj collection = CreateCollection(collType); - _storages.Add(name, collection); + _storages.Add(coll, CreateCollection(collType)); } // Удаление коллекции ( по ключу-строке - её имени ) public void DelCollection(string name) { - if (_storages.ContainsKey(name)) _storages.Remove(name); + // descroption [ ? ] >>> + CollectionInfo coll = new CollectionInfo(name, + CollectionType.None, string.Empty); + + if (_storages.ContainsKey(coll)) _storages.Remove(coll); else throw new NullReferenceException("> No such key in the list"); } - // Доступ к коллекции ( по ключу-строке - её имени ) - индексатор [!!!] + // Доступ к коллекции , индексатор [!!!] public ICollectionGenObj? this[string name] { - get => _storages.ContainsKey(name) ? _storages[name] : null; + get => _storages.ContainsKey(new CollectionInfo(name, CollectionType.None, string.Empty)) + ? _storages[new CollectionInfo(name, CollectionType.None, string.Empty)] : null; } /// Сохранение информации по автомобилям в хранилище в файл @@ -68,15 +70,14 @@ public class StorageCollection sb.Append(_collectionKey); // const - foreach (KeyValuePair> pair in _storages) + foreach (KeyValuePair> pair in _storages) { sb.Append(Environment.NewLine); // не сохраняем пустые коллекции if (pair.Value.Count == 0) { continue; } sb.Append(pair.Key); sb.Append(_separatorForKeyValue); - sb.Append(pair.Value.GetCollectionType); - sb.Append(_separatorForKeyValue); + // <...> sb.Append(pair.Value.MaxCount); sb.Append(_separatorForKeyValue); @@ -144,18 +145,19 @@ public class StorageCollection foreach (string data in companies) { string[] record = data.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); - if (record.Length != 4) // > - // key | collType | maxcount | all next inf > 4 + if (record.Length != 3) // > + // [key + collType] | maxcount | all next inf > 4 { continue; } - CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]); - ICollectionGenObj? collection = StorageCollection.CreateCollection(collectionType); - - if (collection == null) - throw new NullReferenceException("[!] Failed to create collection"); + CollectionInfo? collInfo = CollectionInfo.GetCollectionInfo(record[0]) ?? + throw new Exception("[!] Failed to decode information : " + record[0]); - collection.MaxCount = Convert.ToInt32(record[2]); - string[] set = record[3].Split(_separatorItems, + ICollectionGenObj? collection = StorageCollection.CreateCollection( + collInfo.CollectionType) ?? + throw new Exception("[!] Failed to create a collection"); + + collection.MaxCount = Convert.ToInt32(record[1]); + string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); foreach (string elem in set) @@ -165,10 +167,6 @@ public class StorageCollection try { collection.Insert(ship); - - // throw new IndexOutOfRangeException IF IT WAS Insert(item, pos) - // NullReferenceException > - // CollectionOverflowException > } catch (Exception e) { @@ -176,7 +174,7 @@ public class StorageCollection } } } - _storages.Add(record[0], collection); + _storages.Add(collInfo, collection); } } } diff --git a/ProjectCruiser/DrawningSamples/DrawningShipCompare.cs b/ProjectCruiser/DrawningSamples/DrawningShipCompare.cs new file mode 100644 index 0000000..3792ba9 --- /dev/null +++ b/ProjectCruiser/DrawningSamples/DrawningShipCompare.cs @@ -0,0 +1,30 @@ +namespace ProjectCruiser.DrawningSamples; + +// Сравнение по типу, скорости, весу +public class DrawningShipCompare : IComparer +{ + public int Compare(DrawningBase? x, DrawningBase? y) + { + if (x == null || x.EntityTransport == null) + { + return -1; + } + if (y == null || y.EntityTransport == null) + { + return 1; + } + if (x.GetType().Name != y.GetType().Name) + { + return x.GetType().Name.CompareTo(y.GetType().Name); + } + + var speedCompare = x.EntityTransport.Speed.CompareTo(y.EntityTransport.Speed); + + if (speedCompare != 0) + { + return speedCompare; + } + + return x.EntityTransport.Weight.CompareTo(y.EntityTransport.Weight); + } +} diff --git a/ProjectCruiser/DrawningSamples/DrawningShipCompareByColor.cs b/ProjectCruiser/DrawningSamples/DrawningShipCompareByColor.cs new file mode 100644 index 0000000..34d26c4 --- /dev/null +++ b/ProjectCruiser/DrawningSamples/DrawningShipCompareByColor.cs @@ -0,0 +1,34 @@ +namespace ProjectCruiser.DrawningSamples; + +public class DrawningShipCompareByColor : IComparer +{ + public int Compare(DrawningBase? x, DrawningBase? y) + { + if (x == null || x.EntityTransport == null) + { + return 1; + } + + if (y == null || y.EntityTransport == null) + { + return -1; + } + + var bodycolorCompare = x.EntityTransport.MainColor.Name.CompareTo( + y.EntityTransport.MainColor.Name); + + if (bodycolorCompare != 0) + { + return bodycolorCompare; + } + + var speedCompare = x.EntityTransport.Speed.CompareTo(y.EntityTransport.Speed); + + if (speedCompare != 0) + { + return speedCompare; + } + + return x.EntityTransport.Weight.CompareTo(y.EntityTransport.Weight); + } +} diff --git a/ProjectCruiser/DrawningSamples/DrawningShipEqutables.cs b/ProjectCruiser/DrawningSamples/DrawningShipEqutables.cs new file mode 100644 index 0000000..fb19dbd --- /dev/null +++ b/ProjectCruiser/DrawningSamples/DrawningShipEqutables.cs @@ -0,0 +1,43 @@ +using System.Diagnostics.CodeAnalysis; +using ProjectCruiser.Entities; + +namespace ProjectCruiser.DrawningSamples; + +// Реализация сравнения двух объектов класса-прорисовки +public class DrawiningShipEqutables : IEqualityComparer +{ + public bool Equals(DrawningBase? x, DrawningBase? y) + { + if (x == null || x.EntityTransport == null) return false; + if (y == null || y.EntityTransport == null) return false; + if (x.GetType().Name != y.GetType().Name) return false; + if (x.EntityTransport.Speed != y.EntityTransport.Speed) return false; + if (x.EntityTransport.Weight != y.EntityTransport.Weight) return false; + if (x.EntityTransport.MainColor != y.EntityTransport.MainColor) return false; + + if (x is DrawningCruiser && y is DrawningCruiser) + { + /* + public Color AdditionalColor { get; private set; } // доп. цвет + // признаки (наличия) + public bool HelicopterPads { get; private set; } // вертолетная площадка + public bool Hangars { get; private set; } // ангар + */ + if (((EntityCruiser)x.EntityTransport).AdditionalColor + != ((EntityCruiser)y.EntityTransport).AdditionalColor) return false; + + if (((EntityCruiser)x.EntityTransport).HelicopterPads + != ((EntityCruiser)y.EntityTransport).HelicopterPads) return false; + + if (((EntityCruiser)x.EntityTransport).Hangars + != ((EntityCruiser)y.EntityTransport).Hangars) return false; + } + + return true; + } + public int GetHashCode([DisallowNull] DrawningBase obj) + { + return obj.GetHashCode(); + } +} + diff --git a/ProjectCruiser/ServiceForm2.Designer.cs b/ProjectCruiser/ServiceForm2.Designer.cs index dc4fd35..8f7eac7 100644 --- a/ProjectCruiser/ServiceForm2.Designer.cs +++ b/ProjectCruiser/ServiceForm2.Designer.cs @@ -52,6 +52,8 @@ loadToolStripMenuItem = new ToolStripMenuItem(); saveFileDialog = new SaveFileDialog(); openFileDialog = new OpenFileDialog(); + btnSortType = new Button(); + btnSortColor = new Button(); groupBox.SuspendLayout(); companyPanel.SuspendLayout(); toolPanel.SuspendLayout(); @@ -64,7 +66,7 @@ comboBoxArrList.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; comboBoxArrList.FormattingEnabled = true; comboBoxArrList.Items.AddRange(new object[] { "Storage" }); - comboBoxArrList.Location = new Point(17, 51); + comboBoxArrList.Location = new Point(17, 38); comboBoxArrList.Name = "comboBoxArrList"; comboBoxArrList.Size = new Size(241, 40); comboBoxArrList.TabIndex = 0; @@ -77,9 +79,9 @@ groupBox.Controls.Add(toolPanel); groupBox.Controls.Add(btnCreateCompany); groupBox.Controls.Add(comboBoxArrList); - groupBox.Location = new Point(1421, 47); + groupBox.Location = new Point(1421, 43); groupBox.Name = "groupBox"; - groupBox.Size = new Size(273, 934); + groupBox.Size = new Size(273, 964); groupBox.TabIndex = 2; groupBox.TabStop = false; groupBox.Text = "Tool panel"; @@ -93,17 +95,17 @@ companyPanel.Controls.Add(rBtnArray); companyPanel.Controls.Add(maskedTxtBoxCName); companyPanel.Controls.Add(label); - companyPanel.Location = new Point(17, 98); + companyPanel.Location = new Point(17, 83); companyPanel.Name = "companyPanel"; - companyPanel.Size = new Size(243, 391); + companyPanel.Size = new Size(243, 359); companyPanel.TabIndex = 7; // // btnDeleteCollection // btnDeleteCollection.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; - btnDeleteCollection.Location = new Point(15, 312); + btnDeleteCollection.Location = new Point(16, 276); btnDeleteCollection.Name = "btnDeleteCollection"; - btnDeleteCollection.Size = new Size(214, 73); + btnDeleteCollection.Size = new Size(214, 76); btnDeleteCollection.TabIndex = 11; btnDeleteCollection.Text = "Remove Collection"; btnDeleteCollection.UseVisualStyleBackColor = true; @@ -112,17 +114,17 @@ // listBox // listBox.FormattingEnabled = true; - listBox.Location = new Point(16, 174); + listBox.Location = new Point(16, 171); listBox.Name = "listBox"; - listBox.Size = new Size(214, 132); + listBox.Size = new Size(214, 100); listBox.TabIndex = 10; // // btnAddCollection // btnAddCollection.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; - btnAddCollection.Location = new Point(15, 119); + btnAddCollection.Location = new Point(15, 118); btnAddCollection.Name = "btnAddCollection"; - btnAddCollection.Size = new Size(214, 50); + btnAddCollection.Size = new Size(214, 49); btnAddCollection.TabIndex = 7; btnAddCollection.Text = "Add Collection"; btnAddCollection.UseVisualStyleBackColor = true; @@ -142,7 +144,7 @@ // rBtnArray // rBtnArray.AutoSize = true; - rBtnArray.Location = new Point(16, 80); + rBtnArray.Location = new Point(16, 79); rBtnArray.Name = "rBtnArray"; rBtnArray.Size = new Size(100, 36); rBtnArray.TabIndex = 8; @@ -169,23 +171,25 @@ // // toolPanel // + toolPanel.Controls.Add(btnSortColor); + toolPanel.Controls.Add(btnSortType); toolPanel.Controls.Add(btnUpdate); toolPanel.Controls.Add(btnTest); toolPanel.Controls.Add(maskedTextBoxPosition); toolPanel.Controls.Add(btnDelete); toolPanel.Controls.Add(btnAddCruiser); toolPanel.Enabled = false; - toolPanel.Location = new Point(26, 608); + toolPanel.Location = new Point(26, 537); toolPanel.Name = "toolPanel"; - toolPanel.Size = new Size(226, 317); + toolPanel.Size = new Size(226, 415); toolPanel.TabIndex = 13; // // btnUpdate // btnUpdate.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; - btnUpdate.Location = new Point(16, 257); + btnUpdate.Location = new Point(16, 350); btnUpdate.Name = "btnUpdate"; - btnUpdate.Size = new Size(192, 41); + btnUpdate.Size = new Size(193, 57); btnUpdate.TabIndex = 6; btnUpdate.Text = "Update"; btnUpdate.UseVisualStyleBackColor = true; @@ -194,9 +198,9 @@ // btnTest // btnTest.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; - btnTest.Location = new Point(17, 162); + btnTest.Location = new Point(17, 142); btnTest.Name = "btnTest"; - btnTest.Size = new Size(192, 89); + btnTest.Size = new Size(192, 80); btnTest.TabIndex = 5; btnTest.Text = "Choose\r\nfor testing"; btnTest.UseVisualStyleBackColor = true; @@ -205,7 +209,7 @@ // maskedTextBoxPosition // maskedTextBoxPosition.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; - maskedTextBoxPosition.Location = new Point(17, 68); + maskedTextBoxPosition.Location = new Point(17, 55); maskedTextBoxPosition.Mask = "00"; maskedTextBoxPosition.Name = "maskedTextBoxPosition"; maskedTextBoxPosition.Size = new Size(192, 39); @@ -215,9 +219,9 @@ // btnDelete // btnDelete.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; - btnDelete.Location = new Point(16, 113); + btnDelete.Location = new Point(17, 99); btnDelete.Name = "btnDelete"; - btnDelete.Size = new Size(192, 43); + btnDelete.Size = new Size(192, 41); btnDelete.TabIndex = 4; btnDelete.Text = "Delete"; btnDelete.UseVisualStyleBackColor = true; @@ -226,9 +230,9 @@ // btnAddCruiser // btnAddCruiser.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; - btnAddCruiser.Location = new Point(17, 13); + btnAddCruiser.Location = new Point(16, 4); btnAddCruiser.Name = "btnAddCruiser"; - btnAddCruiser.Size = new Size(192, 49); + btnAddCruiser.Size = new Size(192, 48); btnAddCruiser.TabIndex = 2; btnAddCruiser.Text = "Add cruiser"; btnAddCruiser.UseVisualStyleBackColor = true; @@ -237,9 +241,9 @@ // btnCreateCompany // btnCreateCompany.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; - btnCreateCompany.Location = new Point(16, 510); + btnCreateCompany.Location = new Point(17, 447); btnCreateCompany.Name = "btnCreateCompany"; - btnCreateCompany.Size = new Size(245, 79); + btnCreateCompany.Size = new Size(245, 85); btnCreateCompany.TabIndex = 12; btnCreateCompany.Text = "Create or switch to Company"; btnCreateCompany.UseVisualStyleBackColor = true; @@ -295,6 +299,28 @@ // openFileDialog.Filter = "txt file|*.txt"; // + // btnSortType + // + btnSortType.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; + btnSortType.Location = new Point(16, 232); + btnSortType.Name = "btnSortType"; + btnSortType.Size = new Size(192, 52); + btnSortType.TabIndex = 7; + btnSortType.Text = "Sort by type"; + btnSortType.UseVisualStyleBackColor = true; + btnSortType.Click += btnSortType_Click; + // + // btnSortColor + // + btnSortColor.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; + btnSortColor.Location = new Point(16, 285); + btnSortColor.Name = "btnSortColor"; + btnSortColor.Size = new Size(192, 52); + btnSortColor.TabIndex = 8; + btnSortColor.Text = "Sort by color"; + btnSortColor.UseVisualStyleBackColor = true; + btnSortColor.Click += btnSortColor_Click; + // // ServiceForm2 // AutoScaleDimensions = new SizeF(13F, 32F); @@ -344,5 +370,7 @@ private ToolStripMenuItem loadToolStripMenuItem; private SaveFileDialog saveFileDialog; private OpenFileDialog openFileDialog; + private Button btnSortColor; + private Button btnSortType; } } \ No newline at end of file diff --git a/ProjectCruiser/ServiceForm2.cs b/ProjectCruiser/ServiceForm2.cs index dfeae24..f96e17d 100644 --- a/ProjectCruiser/ServiceForm2.cs +++ b/ProjectCruiser/ServiceForm2.cs @@ -177,7 +177,8 @@ public partial class ServiceForm2 : Form { MessageBox.Show("Collection was not choosed"); return; - } if (MessageBox.Show("Are you sure?", "Removing", + } + if (MessageBox.Show("Are you sure?", "Removing", MessageBoxButtons.OK, MessageBoxIcon.Question) != DialogResult.OK) return; @@ -199,7 +200,8 @@ public partial class ServiceForm2 : Form listBox.Items.Clear(); for (int i = 0; i < _storageCollection.Keys?.Count; ++i) { - string? collName = _storageCollection.Keys?[i]; + string? collName = _storageCollection.Keys?[i].Name; + if (!string.IsNullOrEmpty(collName)) { listBox.Items.Add(collName); @@ -264,12 +266,6 @@ public partial class ServiceForm2 : Form try { _storageCollection.LoadData(openFileDialog.FileName); - // LoadData() : Exceptions - // FileNotFoundException - // NullReferenceException - // InvalidDataException - // IndexOutOfRangeException - // CollectionOverflowException MessageBox.Show(" < Loaded succesfully >", "Result :", MessageBoxButtons.OK, MessageBoxIcon.Information); @@ -285,4 +281,25 @@ public partial class ServiceForm2 : Form } } } + + // Сортировка по сравнителю + private void CompareShips(IComparer comparer) + { + if (_company == null) + { + return; + } + _company.Sort(comparer); + pictureBox.Image = _company.Show(); + } + + private void btnSortType_Click(object sender, EventArgs e) + { + CompareShips(new DrawningShipCompare()); + } + + private void btnSortColor_Click(object sender, EventArgs e) + { + CompareShips(new DrawningShipCompareByColor()); + } }