From e2ac931dfd686c1701a34cf075f9eb1ae0d93944 Mon Sep 17 00:00:00 2001 From: K Date: Tue, 12 Dec 2023 17:42:31 +0300 Subject: [PATCH 1/3] lab_8 --- speed_Boat/speed_Boat/BoatCompareByColor.cs | 55 ++++++++++ speed_Boat/speed_Boat/BoatCompareByType.cs | 35 ++++++ speed_Boat/speed_Boat/BoatsCollectionInfo.cs | 28 +++++ .../speed_Boat/BoatsGenericCollection.cs | 7 +- speed_Boat/speed_Boat/BoatsGenericStorage.cs | 31 +++--- speed_Boat/speed_Boat/DrawingBoatEquatable.cs | 66 ++++++++++++ .../speed_Boat/FormBoatCollection.Designer.cs | 62 +++++++++-- speed_Boat/speed_Boat/FormBoatCollection.cs | 102 +++++++++++++++--- speed_Boat/speed_Boat/GenericClass.cs | 57 +++++----- speed_Boat/speed_Boat/nlog.config | 13 --- 10 files changed, 370 insertions(+), 86 deletions(-) create mode 100644 speed_Boat/speed_Boat/BoatCompareByColor.cs create mode 100644 speed_Boat/speed_Boat/BoatCompareByType.cs create mode 100644 speed_Boat/speed_Boat/BoatsCollectionInfo.cs create mode 100644 speed_Boat/speed_Boat/DrawingBoatEquatable.cs delete mode 100644 speed_Boat/speed_Boat/nlog.config diff --git a/speed_Boat/speed_Boat/BoatCompareByColor.cs b/speed_Boat/speed_Boat/BoatCompareByColor.cs new file mode 100644 index 0000000..4e07392 --- /dev/null +++ b/speed_Boat/speed_Boat/BoatCompareByColor.cs @@ -0,0 +1,55 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using SpeedBoatLab.Drawings; +using SpeedBoatLab.Entity; + +namespace speed_Boat.Generics +{ + internal class BoatCompareByColor : IComparer + { + public int Compare(DrawingBoat? x, DrawingBoat? y) + { + // TODO реализовать логику сравнения + if (x == null || x._entityBoat == null) + { + throw new ArgumentNullException(nameof(x)); + } + if (y == null || y._entityBoat == null) + { + throw new ArgumentNullException(nameof(y)); + } + if(x._entityBoat.MainColor.Name != y._entityBoat.MainColor.Name) + { + return x._entityBoat.MainColor.Name.CompareTo(y._entityBoat.MainColor.Name); + } + if(x.GetType().Name != y.GetType().Name) + { + if (x is DrawingBoat) + return -1; + else + return 1; + } + if(x.GetType().Name == y.GetType().Name && x is DrawingSpeedBoat) + { + EntitySpeedboat _speedboatX = (EntitySpeedboat)x._entityBoat; + EntitySpeedboat _speedboatY = (EntitySpeedboat)y._entityBoat; + + if (_speedboatX.SecondColor.Name != _speedboatY.SecondColor.Name) + { + return _speedboatX.SecondColor.Name.CompareTo(_speedboatY.SecondColor.Name); + } + } + + var speedCompare = x._entityBoat.Speed.CompareTo(y._entityBoat.Speed); + if (speedCompare != 0) + { + return speedCompare; + } + return x._entityBoat.Weight.CompareTo(y._entityBoat.Weight); + + } + } +} diff --git a/speed_Boat/speed_Boat/BoatCompareByType.cs b/speed_Boat/speed_Boat/BoatCompareByType.cs new file mode 100644 index 0000000..e643247 --- /dev/null +++ b/speed_Boat/speed_Boat/BoatCompareByType.cs @@ -0,0 +1,35 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using SpeedBoatLab.Drawings; + +namespace speed_Boat.Generics +{ + internal class BoatCompareByType : IComparer + { + public int Compare(DrawingBoat? x, DrawingBoat? y) + { + if (x == null || x._entityBoat == null) + { + throw new ArgumentNullException(nameof(x)); + } + if (y == null || y._entityBoat == null) + { + throw new ArgumentNullException(nameof(y)); + } + if (x.GetType().Name != y.GetType().Name) + { + return x.GetType().Name.CompareTo(y.GetType().Name); + } + var speedCompare = x._entityBoat.Speed.CompareTo(y._entityBoat.Speed); + if (speedCompare != 0) + { + return speedCompare; + } + return x._entityBoat.Weight.CompareTo(y._entityBoat.Weight); + } + + } +} diff --git a/speed_Boat/speed_Boat/BoatsCollectionInfo.cs b/speed_Boat/speed_Boat/BoatsCollectionInfo.cs new file mode 100644 index 0000000..b6f4ee0 --- /dev/null +++ b/speed_Boat/speed_Boat/BoatsCollectionInfo.cs @@ -0,0 +1,28 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace speed_Boat.Generics +{ + internal class BoatsCollectionInfo : IEquatable + { + public string Name { get; private set; } + public string Description { get; private set; } + public BoatsCollectionInfo(string name, string description) + { + Name = name; + Description = description; + } + public bool Equals(BoatsCollectionInfo? other) + { + // TODO прописать логику сравнения по свойству Name + return Name == other.Name; + } + public override int GetHashCode() + { + return this.Name.GetHashCode(); + } + } +} diff --git a/speed_Boat/speed_Boat/BoatsGenericCollection.cs b/speed_Boat/speed_Boat/BoatsGenericCollection.cs index e1b1730..01b65a4 100644 --- a/speed_Boat/speed_Boat/BoatsGenericCollection.cs +++ b/speed_Boat/speed_Boat/BoatsGenericCollection.cs @@ -18,6 +18,11 @@ namespace speed_Boat.Generics /// public IEnumerable GetBoats => _collection.GetBoats(); /// + /// Сортировка + /// + /// + public void Sort(IComparer comparer) => _collection.SortSet(comparer); + /// /// Ширина окна прорисовки /// private readonly int _pictureWidth; @@ -56,7 +61,7 @@ namespace speed_Boat.Generics { if (obj != null) { - return collect?._collection.Insert(obj) ?? -1; + return collect?._collection.Insert(obj, new DrawingBoatEquatable()) ?? -1; } return 0; } diff --git a/speed_Boat/speed_Boat/BoatsGenericStorage.cs b/speed_Boat/speed_Boat/BoatsGenericStorage.cs index 0bf67c2..bd6905a 100644 --- a/speed_Boat/speed_Boat/BoatsGenericStorage.cs +++ b/speed_Boat/speed_Boat/BoatsGenericStorage.cs @@ -16,14 +16,14 @@ namespace speed_Boat.Generics /// internal class BoatsGenericStorage { - /// - /// Словарь(хранилище) + /// + /// Словарь (хранилище) /// - readonly Dictionary> _boatStorages; + readonly Dictionary> _boatStorages; /// /// Возвращение списка названий наборов /// - public List Keys => _boatStorages.Keys.ToList(); + public List Keys => _boatStorages.Keys.ToList(); /// /// Ширина окна отрисовки /// @@ -51,7 +51,7 @@ namespace speed_Boat.Generics /// public BoatsGenericStorage(int pictureWidth, int pictureHeight) { - _boatStorages = new Dictionary>(); + _boatStorages = new Dictionary>(); _pictureWidth = pictureWidth; _pictureHeight = pictureHeight; } @@ -71,14 +71,14 @@ namespace speed_Boat.Generics File.Delete(filename); } StringBuilder data = new(); - foreach (KeyValuePair> record in _boatStorages) + foreach (KeyValuePair> record in _boatStorages) { StringBuilder records = new(); foreach (DrawingBoat? elem in record.Value.GetBoats) { records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}"); } - data.AppendLine($"{record.Key}{_separatorForKeyValue}{records}"); + data.AppendLine($"{record.Key.Name}{_separatorForKeyValue}{records}"); } if(data.Length == 0) { @@ -139,7 +139,7 @@ namespace speed_Boat.Generics } } } - _boatStorages.Add(record[0], collection); + _boatStorages.Add(new BoatsCollectionInfo(record[0], string.Empty), collection); str = sr.ReadLine(); } while (str != null); } @@ -151,14 +151,14 @@ namespace speed_Boat.Generics /// public void AddSet(string name) { - if (_boatStorages.ContainsKey(name)) + if (_boatStorages.ContainsKey(new BoatsCollectionInfo(name, string.Empty))) { MessageBox.Show("Словарь уже содержит набор с таким названием", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); } else { - _boatStorages.Add(name, new BoatsGenericCollection(_pictureWidth, _pictureHeight)); + _boatStorages.Add(new BoatsCollectionInfo(name, string.Empty), new BoatsGenericCollection(_pictureWidth, _pictureHeight)); } } /// @@ -168,9 +168,9 @@ namespace speed_Boat.Generics public void DelSet(string name) { BoatsGenericCollection boat; - if (_boatStorages.TryGetValue(name, out boat)) + if (_boatStorages.TryGetValue(new BoatsCollectionInfo(name, string.Empty), out boat)) { - _boatStorages.Remove(name); + _boatStorages.Remove(new BoatsCollectionInfo(name, string.Empty)); } } /// @@ -182,11 +182,10 @@ namespace speed_Boat.Generics { get { - BoatsGenericCollection boat; - //проверка есть ли в словаре обьект с ключом ind - if (_boatStorages.TryGetValue(ind, out boat)) + BoatsCollectionInfo infBoat = new BoatsCollectionInfo(ind, string.Empty); + if(_boatStorages.ContainsKey(infBoat)) { - return boat; + return _boatStorages[infBoat]; } return null; } diff --git a/speed_Boat/speed_Boat/DrawingBoatEquatable.cs b/speed_Boat/speed_Boat/DrawingBoatEquatable.cs new file mode 100644 index 0000000..d18ad0d --- /dev/null +++ b/speed_Boat/speed_Boat/DrawingBoatEquatable.cs @@ -0,0 +1,66 @@ +using SpeedBoatLab.Drawings; +using SpeedBoatLab.Entity; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace speed_Boat.Generics +{ + internal class DrawingBoatEquatable : IEqualityComparer + { + public bool Equals(DrawingBoat? x, DrawingBoat? y) + { + if (x == null || x._entityBoat == null) + { + throw new ArgumentNullException(nameof(x)); + } + if (y == null || y._entityBoat == null) + { + throw new ArgumentNullException(nameof(y)); + } + if (x.GetType().Name != y.GetType().Name) + { + return false; + } + if (x._entityBoat.Speed != y._entityBoat.Speed) + { + return false; + } + if (x._entityBoat.Weight != y._entityBoat.Weight) + { + return false; + } + if (x._entityBoat.MainColor != y._entityBoat.MainColor) + { + return false; + } + if (x is DrawingSpeedBoat && y is DrawingSpeedBoat) + { + // TODO доделать логику сравнения дополнительных параметров + EntitySpeedboat _speedboatX = (EntitySpeedboat)x._entityBoat; + EntitySpeedboat _speedboatY = (EntitySpeedboat)y._entityBoat; + if (_speedboatX.isMotor != _speedboatY.isMotor) + { + return false; + } + if (_speedboatX.isProtectedGlass != _speedboatY.isProtectedGlass) + { + return false; + } + if(_speedboatX.SecondColor != _speedboatY.SecondColor) + { + return false; + } + } + return true; + } + public int GetHashCode([DisallowNull] DrawingBoat obj) + { + return obj.GetHashCode(); + } + + } +} diff --git a/speed_Boat/speed_Boat/FormBoatCollection.Designer.cs b/speed_Boat/speed_Boat/FormBoatCollection.Designer.cs index 38de93d..683295d 100644 --- a/speed_Boat/speed_Boat/FormBoatCollection.Designer.cs +++ b/speed_Boat/speed_Boat/FormBoatCollection.Designer.cs @@ -30,6 +30,9 @@ namespace SpeedBoatLab private void InitializeComponent() { groupBox1 = new System.Windows.Forms.GroupBox(); + groupBox3 = new System.Windows.Forms.GroupBox(); + button1 = new System.Windows.Forms.Button(); + button2 = new System.Windows.Forms.Button(); groupBox2 = new System.Windows.Forms.GroupBox(); deleteStorageButton = new System.Windows.Forms.Button(); storagesListBox = new System.Windows.Forms.ListBox(); @@ -48,6 +51,7 @@ namespace SpeedBoatLab openFileDialog = new System.Windows.Forms.OpenFileDialog(); saveFileDialog = new System.Windows.Forms.SaveFileDialog(); groupBox1.SuspendLayout(); + groupBox3.SuspendLayout(); groupBox2.SuspendLayout(); menuStrip1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)pictureBoxCollection).BeginInit(); @@ -55,6 +59,7 @@ namespace SpeedBoatLab // // groupBox1 // + groupBox1.Controls.Add(groupBox3); groupBox1.Controls.Add(groupBox2); groupBox1.Controls.Add(label1); groupBox1.Controls.Add(maskedTextBoxNumber); @@ -64,11 +69,42 @@ namespace SpeedBoatLab groupBox1.Controls.Add(menuStrip1); groupBox1.Location = new System.Drawing.Point(581, 2); groupBox1.Name = "groupBox1"; - groupBox1.Size = new System.Drawing.Size(205, 471); + groupBox1.Size = new System.Drawing.Size(205, 586); groupBox1.TabIndex = 0; groupBox1.TabStop = false; groupBox1.Text = "Настройки"; // + // groupBox3 + // + groupBox3.Controls.Add(button1); + groupBox3.Controls.Add(button2); + groupBox3.Location = new System.Drawing.Point(6, 439); + groupBox3.Name = "groupBox3"; + groupBox3.Size = new System.Drawing.Size(193, 102); + groupBox3.TabIndex = 7; + groupBox3.TabStop = false; + groupBox3.Text = "Сортировки"; + // + // button1 + // + button1.Location = new System.Drawing.Point(6, 61); + button1.Name = "button1"; + button1.Size = new System.Drawing.Size(181, 29); + button1.TabIndex = 7; + button1.Text = "Сортировка по типу"; + button1.UseVisualStyleBackColor = true; + button1.Click += ButtonSortByType_Click; + // + // button2 + // + button2.Location = new System.Drawing.Point(6, 26); + button2.Name = "button2"; + button2.Size = new System.Drawing.Size(181, 29); + button2.TabIndex = 8; + button2.Text = "Сортировка по цвету"; + button2.UseVisualStyleBackColor = true; + button2.Click += ButtonSortByColor_Click; + // // groupBox2 // groupBox2.Controls.Add(deleteStorageButton); @@ -122,7 +158,7 @@ namespace SpeedBoatLab // label1 // label1.AutoSize = true; - label1.Location = new System.Drawing.Point(6, 299); + label1.Location = new System.Drawing.Point(6, 308); label1.Name = "label1"; label1.Size = new System.Drawing.Size(135, 20); label1.TabIndex = 4; @@ -130,14 +166,14 @@ namespace SpeedBoatLab // // maskedTextBoxNumber // - maskedTextBoxNumber.Location = new System.Drawing.Point(6, 322); + maskedTextBoxNumber.Location = new System.Drawing.Point(6, 331); maskedTextBoxNumber.Name = "maskedTextBoxNumber"; maskedTextBoxNumber.Size = new System.Drawing.Size(193, 27); maskedTextBoxNumber.TabIndex = 3; // // UpdateCollectionButton // - UpdateCollectionButton.Location = new System.Drawing.Point(6, 391); + UpdateCollectionButton.Location = new System.Drawing.Point(6, 400); UpdateCollectionButton.Name = "UpdateCollectionButton"; UpdateCollectionButton.Size = new System.Drawing.Size(193, 29); UpdateCollectionButton.TabIndex = 2; @@ -147,7 +183,7 @@ namespace SpeedBoatLab // // DeleteBoatButton // - DeleteBoatButton.Location = new System.Drawing.Point(6, 355); + DeleteBoatButton.Location = new System.Drawing.Point(6, 364); DeleteBoatButton.Name = "DeleteBoatButton"; DeleteBoatButton.Size = new System.Drawing.Size(193, 30); DeleteBoatButton.TabIndex = 1; @@ -157,7 +193,7 @@ namespace SpeedBoatLab // // AddBoatButton // - AddBoatButton.Location = new System.Drawing.Point(6, 268); + AddBoatButton.Location = new System.Drawing.Point(6, 277); AddBoatButton.Name = "AddBoatButton"; AddBoatButton.Size = new System.Drawing.Size(193, 28); AddBoatButton.TabIndex = 0; @@ -170,7 +206,7 @@ namespace SpeedBoatLab menuStrip1.Dock = System.Windows.Forms.DockStyle.Bottom; menuStrip1.ImageScalingSize = new System.Drawing.Size(20, 20); menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { файлToolStripMenuItem }); - menuStrip1.Location = new System.Drawing.Point(3, 440); + menuStrip1.Location = new System.Drawing.Point(3, 555); menuStrip1.Name = "menuStrip1"; menuStrip1.Size = new System.Drawing.Size(199, 28); menuStrip1.TabIndex = 6; @@ -186,14 +222,14 @@ namespace SpeedBoatLab // загрузкаToolStripMenuItem // загрузкаToolStripMenuItem.Name = "загрузкаToolStripMenuItem"; - загрузкаToolStripMenuItem.Size = new System.Drawing.Size(224, 26); + загрузкаToolStripMenuItem.Size = new System.Drawing.Size(177, 26); загрузкаToolStripMenuItem.Text = "Загрузка"; загрузкаToolStripMenuItem.Click += LoadToolStripMenuItem_Click; // // сохранениеToolStripMenuItem // сохранениеToolStripMenuItem.Name = "сохранениеToolStripMenuItem"; - сохранениеToolStripMenuItem.Size = new System.Drawing.Size(224, 26); + сохранениеToolStripMenuItem.Size = new System.Drawing.Size(177, 26); сохранениеToolStripMenuItem.Text = "Сохранение"; сохранениеToolStripMenuItem.Click += SaveToolStripMenuItem_Click; // @@ -201,7 +237,7 @@ namespace SpeedBoatLab // pictureBoxCollection.Location = new System.Drawing.Point(12, 12); pictureBoxCollection.Name = "pictureBoxCollection"; - pictureBoxCollection.Size = new System.Drawing.Size(554, 527); + pictureBoxCollection.Size = new System.Drawing.Size(554, 576); pictureBoxCollection.TabIndex = 1; pictureBoxCollection.TabStop = false; // @@ -218,7 +254,7 @@ namespace SpeedBoatLab // AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F); AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; - ClientSize = new System.Drawing.Size(800, 551); + ClientSize = new System.Drawing.Size(800, 600); Controls.Add(pictureBoxCollection); Controls.Add(groupBox1); MainMenuStrip = menuStrip1; @@ -226,6 +262,7 @@ namespace SpeedBoatLab Text = "Коллекция катеров"; groupBox1.ResumeLayout(false); groupBox1.PerformLayout(); + groupBox3.ResumeLayout(false); groupBox2.ResumeLayout(false); groupBox2.PerformLayout(); menuStrip1.ResumeLayout(false); @@ -254,5 +291,8 @@ namespace SpeedBoatLab private System.Windows.Forms.ToolStripMenuItem сохранениеToolStripMenuItem; private System.Windows.Forms.OpenFileDialog openFileDialog; private System.Windows.Forms.SaveFileDialog saveFileDialog; + private System.Windows.Forms.GroupBox groupBox3; + private System.Windows.Forms.Button button1; + private System.Windows.Forms.Button button2; } } \ No newline at end of file diff --git a/speed_Boat/speed_Boat/FormBoatCollection.cs b/speed_Boat/speed_Boat/FormBoatCollection.cs index a00d935..cc93d20 100644 --- a/speed_Boat/speed_Boat/FormBoatCollection.cs +++ b/speed_Boat/speed_Boat/FormBoatCollection.cs @@ -49,7 +49,7 @@ namespace SpeedBoatLab for (int i = 0; i < _storage.Keys.Count; i++) { - storagesListBox.Items.Add(_storage.Keys[i]); + storagesListBox.Items.Add(_storage.Keys[i].Name); } if (storagesListBox.Items.Count > 0 && (index == -1 || @@ -73,13 +73,12 @@ namespace SpeedBoatLab if (string.IsNullOrEmpty(nameStorageTextBox.Text)) { MessageBox.Show("Не все данные заполнены", "Ошибка", - MessageBoxButtons.OK, MessageBoxIcon.Error); - _logger.LogWarning("Пустое название набора"); + MessageBoxButtons.OK, MessageBoxIcon.Error); return; } _storage.AddSet(nameStorageTextBox.Text); ReloadObjects(); - _logger.LogInformation($"Добавлен набор:{nameStorageTextBox.Text}"); + _logger.LogInformation($"Добавлен набор: {nameStorageTextBox.Text}"); } /// @@ -122,15 +121,49 @@ namespace SpeedBoatLab { if (storagesListBox.SelectedIndex == -1) { - _logger.LogWarning("Набор для добавления обьекта не выбран"); return; } - var FormBoatConfig = new FormBoatConfig(); - FormBoatConfig.AddEvent(new(AddBoat)); - FormBoatConfig.Show(); + var obj = _storage[storagesListBox.SelectedItem.ToString() ?? + string.Empty]; + if (obj == null) + { + return; + } + FormBoatConfig form = new(); + form.Show(); + Action? boatDelegate = new((boat) => + { + try + { + _ = obj + boat; + MessageBox.Show("Объект добавлен"); + _logger.LogInformation($"Добавлен объект в коллекцию {storagesListBox.SelectedItem.ToString() ?? string.Empty}"); + pictureBoxCollection.Image = obj.ShowBoats(); + } + catch (StorageOverflowException ex) + { + _logger.LogWarning($"Коллекция {storagesListBox.SelectedItem.ToString() ?? string.Empty} переполнена"); + MessageBox.Show(ex.Message); + } + catch (ArgumentException ex) + { + _logger.LogWarning($"Добавляемый объект уже существует в коллекции {storagesListBox.SelectedItem.ToString() ?? string.Empty}"); + MessageBox.Show("Добавляемый объект уже сущесвует в коллекции"); + } + }); + form.AddEvent(boatDelegate); + /* if (storagesListBox.SelectedIndex == -1) + { + _logger.LogWarning("Набор для добавления обьекта не выбран"); + return; + } + var FormBoatConfig = new FormBoatConfig(); + + FormBoatConfig.Show(); + FormBoatConfig.AddEvent(new(AddBoat));*/ } - public void AddBoat(DrawingBoat? boat) + /* public void AddBoat(DrawingBoat? boat) { if (storagesListBox.SelectedIndex == -1) { @@ -147,15 +180,20 @@ namespace SpeedBoatLab { _ = obj + boat; MessageBox.Show("Объект добавлен"); - _logger.LogInformation($"Добавлен объект в набор {storagesListBox.SelectedItem.ToString()}"); + _logger.LogInformation($"Добавлен объект в набор {storagesListBox.SelectedItem.ToString() ?? string.Empty}"); pictureBoxCollection.Image = obj.ShowBoats(); } - catch(StorageOverflowException ex) + catch (StorageOverflowException ex) { MessageBox.Show("Не удалось добавить объект"); - _logger.LogWarning($"{ex.Message} в наборе {storagesListBox.SelectedItem.ToString()}"); + _logger.LogWarning($"{ex.Message} в наборе {storagesListBox.SelectedItem.ToString() ?? string.Empty}"); } - } + catch (ArgumentException ex) + { + MessageBox.Show("Добавляемый объект уже существует в коллекции"); + _logger.LogWarning($"Добавляемый объект уже существует в коллекции {storagesListBox.SelectedItem.ToString() ?? string.Empty}"); + } + }*/ /// /// Удаление объекта из набора @@ -203,13 +241,13 @@ namespace SpeedBoatLab _logger.LogInformation($"Не удалось удалить объект из набора {storagesListBox.SelectedItem.ToString()}"); } } - catch(BoatNotFoundException ex) + catch (BoatNotFoundException ex) { MessageBox.Show(ex.Message); _logger.LogWarning($"{ex.Message} из набора {storagesListBox.SelectedItem.ToString()}"); } } - else if(insertPosition == string.Empty) + else if (insertPosition == string.Empty) { MessageBox.Show("Неверный формат позиции"); _logger.LogWarning($"Неверный формат позиции:{insertPosition}"); @@ -285,5 +323,39 @@ namespace SpeedBoatLab } + /// + /// Сортировка по типу + /// + /// + /// + private void ButtonSortByType_Click(object sender, EventArgs e) => CompareBoats(new BoatCompareByType()); + + /// + /// Сортировка по цвету + /// + /// + /// + private void ButtonSortByColor_Click(object sender, EventArgs e) => CompareBoats(new BoatCompareByColor()); + + /// + /// Сортировка по сравнителю + /// + /// + private void CompareBoats(IComparer comparer) + { + if (storagesListBox.SelectedIndex == -1) + { + return; + } + var obj = _storage[storagesListBox.SelectedItem.ToString() ?? + string.Empty]; + if (obj == null) + { + return; + } + obj.Sort(comparer); + pictureBoxCollection.Image = obj.ShowBoats(); + } + } } diff --git a/speed_Boat/speed_Boat/GenericClass.cs b/speed_Boat/speed_Boat/GenericClass.cs index 2a71f6a..ffced33 100644 --- a/speed_Boat/speed_Boat/GenericClass.cs +++ b/speed_Boat/speed_Boat/GenericClass.cs @@ -23,7 +23,12 @@ namespace speed_Boat.Generics /// Максимальное количество обьектов в списке /// private readonly int _maxCount; - + /// + /// Сортировка набора объектов + /// + /// + public void SortSet(IComparer comparer) => _places.Sort(comparer); + /// /// Конструктор /// @@ -35,31 +40,12 @@ namespace speed_Boat.Generics /// /// Добавление объекта в набор /// - public int Insert(T boat) + public int Insert(T boat, IEqualityComparer? equal = null) { - if(_places.Count == 0) - { - _places.Add(boat); - return 0; - } - else - { - if (_places.Count < _maxCount) - { - _places.Add(boat); - for(int i = 0; i < _places.Count; i++) - { - T temp = _places[i]; - _places[i] = _places[_places.Count - 1]; - _places[_places.Count - 1] = temp; - } - return 0; - } - else - { - throw new StorageOverflowException(); - } - } + if (_places.Count == _maxCount) + throw new StorageOverflowException(_maxCount); + Insert(boat, 0, equal); + return 0; } /// /// Добавление объекта в набор на конкретную позицию. @@ -67,19 +53,30 @@ namespace speed_Boat.Generics /// Если позиция занята, то происходит сдвиг элементов /// вправо(при возможности) на одну позицию. /// - public bool Insert(T boat, int position) + public bool Insert(T boat, int position, IEqualityComparer? equal = null) { - if (position < 0 || position >= Count) + if (!(position >= 0 && position <= Count)) return false; - if (_places == null) + if (equal != null) + { + if (_places.Contains(boat, equal)) + { + throw new ArgumentException((nameof(boat))); + } + } + if (_places.Count == 0 && position == 0) + { + _places.Add(boat); + return true; + } + + else if (_places.Count == 0 && position != 0) return false; - if (_places[position] == null) { _places[position] = boat; return true; } - if (_places.Count < _maxCount) { _places.Add(boat); diff --git a/speed_Boat/speed_Boat/nlog.config b/speed_Boat/speed_Boat/nlog.config deleted file mode 100644 index ee75e5d..0000000 --- a/speed_Boat/speed_Boat/nlog.config +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - \ No newline at end of file -- 2.25.1 From 6758441ee893577b3b4423f10177528a0f73f687 Mon Sep 17 00:00:00 2001 From: K Date: Sun, 17 Dec 2023 00:53:51 +0300 Subject: [PATCH 2/3] IevlewaMD_lab8 --- speed_Boat/speed_Boat/FormBoatCollection.cs | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/speed_Boat/speed_Boat/FormBoatCollection.cs b/speed_Boat/speed_Boat/FormBoatCollection.cs index cc93d20..aeb5362 100644 --- a/speed_Boat/speed_Boat/FormBoatCollection.cs +++ b/speed_Boat/speed_Boat/FormBoatCollection.cs @@ -337,6 +337,20 @@ namespace SpeedBoatLab /// private void ButtonSortByColor_Click(object sender, EventArgs e) => CompareBoats(new BoatCompareByColor()); + private void CompareStorages(IComparer comparer, string name1, string name2) + { + if (storagesListBox.Items.Count < 2) + { + return; + } + var _storage1 = _storage[name1]; + var _storage2 = _storage[name2]; + + if (_storage1 == null || _storage2 == null) + return; + + + } /// /// Сортировка по сравнителю /// -- 2.25.1 From e544555b7bd39dd9c8f7a56d44463afcf7c2e8a1 Mon Sep 17 00:00:00 2001 From: K Date: Mon, 18 Dec 2023 18:54:06 +0300 Subject: [PATCH 3/3] lab8 --- speed_Boat/speed_Boat/BoatCompareByColor.cs | 7 ------- speed_Boat/speed_Boat/BoatsCollectionInfo.cs | 7 +++++-- 2 files changed, 5 insertions(+), 9 deletions(-) diff --git a/speed_Boat/speed_Boat/BoatCompareByColor.cs b/speed_Boat/speed_Boat/BoatCompareByColor.cs index 4e07392..2b79f69 100644 --- a/speed_Boat/speed_Boat/BoatCompareByColor.cs +++ b/speed_Boat/speed_Boat/BoatCompareByColor.cs @@ -25,13 +25,6 @@ namespace speed_Boat.Generics { return x._entityBoat.MainColor.Name.CompareTo(y._entityBoat.MainColor.Name); } - if(x.GetType().Name != y.GetType().Name) - { - if (x is DrawingBoat) - return -1; - else - return 1; - } if(x.GetType().Name == y.GetType().Name && x is DrawingSpeedBoat) { EntitySpeedboat _speedboatX = (EntitySpeedboat)x._entityBoat; diff --git a/speed_Boat/speed_Boat/BoatsCollectionInfo.cs b/speed_Boat/speed_Boat/BoatsCollectionInfo.cs index b6f4ee0..f3f110b 100644 --- a/speed_Boat/speed_Boat/BoatsCollectionInfo.cs +++ b/speed_Boat/speed_Boat/BoatsCollectionInfo.cs @@ -18,11 +18,14 @@ namespace speed_Boat.Generics public bool Equals(BoatsCollectionInfo? other) { // TODO прописать логику сравнения по свойству Name - return Name == other.Name; + if (Name == other?.Name) + return true; + + return false; } public override int GetHashCode() { - return this.Name.GetHashCode(); + return Name.GetHashCode(); } } } -- 2.25.1