diff --git a/RPP_FirstLaba_Tractor/RPP_FirstLaba_Tractor/DrawningTractorEqutables.cs b/RPP_FirstLaba_Tractor/RPP_FirstLaba_Tractor/DrawningTractorEqutables.cs new file mode 100644 index 0000000..64b29d1 --- /dev/null +++ b/RPP_FirstLaba_Tractor/RPP_FirstLaba_Tractor/DrawningTractorEqutables.cs @@ -0,0 +1,59 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using ProjectTractor.DrawningObjects; +using ProjectTractor.Entities; +using System.Diagnostics.CodeAnalysis; + +namespace ProjectTractor.Generics +{ + internal class DrawningTractorEqutables : IEqualityComparer + { + public bool Equals(DrawningTractor? x, DrawningTractor? y) + { + if (x == null || x.EntityTractor == null) + { + throw new ArgumentNullException(nameof(x)); + } + if (y == null || y.EntityTractor == null) + { + throw new ArgumentNullException(nameof(y)); + } + if (x.GetType().Name != y.GetType().Name) + { + return false; + } + if (x.EntityTractor.Speed != y.EntityTractor.Speed) + { + return false; + } + if (x.EntityTractor.Weight != y.EntityTractor.Weight) + { + return false; + } + if (x.EntityTractor.BodyColor != y.EntityTractor.BodyColor) + { + return false; + } + if (x is DrawningBulldoser && y is DrawningBulldoser) + { + EntityBulldoser EntityX = (EntityBulldoser)x.EntityTractor; + EntityBulldoser EntityY = (EntityBulldoser)y.EntityTractor; + if (EntityX.Blade != EntityY.Blade) + return false; + if (EntityX.WheelsOrnament != EntityY.WheelsOrnament) + return false; + if (EntityX.AdditionalColor != EntityY.AdditionalColor) + return false; + } + return true; + } + public int GetHashCode([DisallowNull] DrawningTractor obj) + { + return obj.GetHashCode(); + } + } +} + diff --git a/RPP_FirstLaba_Tractor/RPP_FirstLaba_Tractor/FormTractorCollection.cs b/RPP_FirstLaba_Tractor/RPP_FirstLaba_Tractor/FormTractorCollection.cs index bbb93a5..85351c8 100644 --- a/RPP_FirstLaba_Tractor/RPP_FirstLaba_Tractor/FormTractorCollection.cs +++ b/RPP_FirstLaba_Tractor/RPP_FirstLaba_Tractor/FormTractorCollection.cs @@ -275,6 +275,8 @@ namespace ProjectTractor { this.pictureBoxCollection = new System.Windows.Forms.PictureBox(); this.groupBox = new System.Windows.Forms.GroupBox(); + this.buttonSortByColor = new System.Windows.Forms.Button(); + this.buttonSortByType = new System.Windows.Forms.Button(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.ButtonDelObject = new System.Windows.Forms.Button(); this.listBoxStorages = new System.Windows.Forms.ListBox(); @@ -306,6 +308,8 @@ namespace ProjectTractor // // groupBox // + this.groupBox.Controls.Add(this.buttonSortByColor); + this.groupBox.Controls.Add(this.buttonSortByType); this.groupBox.Controls.Add(this.groupBox1); this.groupBox.Controls.Add(this.ButtonRefreshCollection); this.groupBox.Controls.Add(this.ButtonRemoveTractor); @@ -319,6 +323,26 @@ namespace ProjectTractor this.groupBox.TabStop = false; this.groupBox.Text = "Инструменты"; // + // buttonSortByColor + // + this.buttonSortByColor.Location = new System.Drawing.Point(28, 321); + this.buttonSortByColor.Name = "buttonSortByColor"; + this.buttonSortByColor.Size = new System.Drawing.Size(203, 34); + this.buttonSortByColor.TabIndex = 12; + this.buttonSortByColor.Text = "Сортировка по цвету"; + this.buttonSortByColor.UseVisualStyleBackColor = true; + this.buttonSortByColor.Click += new System.EventHandler(this.buttonSortByColor_Click); + // + // buttonSortByType + // + this.buttonSortByType.Location = new System.Drawing.Point(28, 279); + this.buttonSortByType.Name = "buttonSortByType"; + this.buttonSortByType.Size = new System.Drawing.Size(203, 34); + this.buttonSortByType.TabIndex = 11; + this.buttonSortByType.Text = "Сортировка по типу"; + this.buttonSortByType.UseVisualStyleBackColor = true; + this.buttonSortByType.Click += new System.EventHandler(this.buttonSortByType_Click); + // // groupBox1 // this.groupBox1.Controls.Add(this.ButtonDelObject); @@ -327,14 +351,14 @@ namespace ProjectTractor this.groupBox1.Controls.Add(this.textBoxStorageName); this.groupBox1.Location = new System.Drawing.Point(16, 54); this.groupBox1.Name = "groupBox1"; - this.groupBox1.Size = new System.Drawing.Size(224, 279); + this.groupBox1.Size = new System.Drawing.Size(224, 229); this.groupBox1.TabIndex = 9; this.groupBox1.TabStop = false; this.groupBox1.Text = "Наборы"; // // ButtonDelObject // - this.ButtonDelObject.Location = new System.Drawing.Point(12, 227); + this.ButtonDelObject.Location = new System.Drawing.Point(12, 184); this.ButtonDelObject.Name = "ButtonDelObject"; this.ButtonDelObject.Size = new System.Drawing.Size(203, 35); this.ButtonDelObject.TabIndex = 3; @@ -346,7 +370,7 @@ namespace ProjectTractor // this.listBoxStorages.FormattingEnabled = true; this.listBoxStorages.ItemHeight = 20; - this.listBoxStorages.Location = new System.Drawing.Point(12, 116); + this.listBoxStorages.Location = new System.Drawing.Point(12, 94); this.listBoxStorages.Name = "listBoxStorages"; this.listBoxStorages.Size = new System.Drawing.Size(203, 84); this.listBoxStorages.TabIndex = 2; @@ -371,7 +395,7 @@ namespace ProjectTractor // // ButtonRefreshCollection // - this.ButtonRefreshCollection.Location = new System.Drawing.Point(28, 463); + this.ButtonRefreshCollection.Location = new System.Drawing.Point(28, 473); this.ButtonRefreshCollection.Name = "ButtonRefreshCollection"; this.ButtonRefreshCollection.Size = new System.Drawing.Size(203, 35); this.ButtonRefreshCollection.TabIndex = 8; @@ -381,7 +405,7 @@ namespace ProjectTractor // // ButtonRemoveTractor // - this.ButtonRemoveTractor.Location = new System.Drawing.Point(28, 410); + this.ButtonRemoveTractor.Location = new System.Drawing.Point(28, 434); this.ButtonRemoveTractor.Name = "ButtonRemoveTractor"; this.ButtonRemoveTractor.Size = new System.Drawing.Size(203, 33); this.ButtonRemoveTractor.TabIndex = 7; @@ -391,7 +415,7 @@ namespace ProjectTractor // // ButtonAddTractor // - this.ButtonAddTractor.Location = new System.Drawing.Point(28, 337); + this.ButtonAddTractor.Location = new System.Drawing.Point(28, 361); this.ButtonAddTractor.Name = "ButtonAddTractor"; this.ButtonAddTractor.Size = new System.Drawing.Size(203, 34); this.ButtonAddTractor.TabIndex = 6; @@ -401,7 +425,7 @@ namespace ProjectTractor // // maskedTextBoxNumber // - this.maskedTextBoxNumber.Location = new System.Drawing.Point(28, 377); + this.maskedTextBoxNumber.Location = new System.Drawing.Point(28, 401); this.maskedTextBoxNumber.Name = "maskedTextBoxNumber"; this.maskedTextBoxNumber.Size = new System.Drawing.Size(203, 27); this.maskedTextBoxNumber.TabIndex = 5; @@ -477,6 +501,43 @@ namespace ProjectTractor private ToolStripMenuItem toolStripMenuItemload; private OpenFileDialog openFileDialog; private SaveFileDialog saveFileDialog; + private Button buttonSortByColor; + private Button buttonSortByType; private PictureBox pictureBoxCollection; + + + /// + /// Сортировка по типу + /// + /// + /// + private void buttonSortByType_Click(object sender, EventArgs e) => CompareTractors(new TractorCompareByType()); + + /// + /// Сортировка по цвету + /// + /// + /// + private void buttonSortByColor_Click(object sender, EventArgs e) => CompareTractors(new TractorCompareByColor()); + + /// + /// Сортировка по сравнителю + /// + /// + private void CompareTractors(IComparer comparer) + { + if (listBoxStorages.SelectedIndex == -1) + { + return; + } + var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? + string.Empty]; + if (obj == null) + { + return; + } + obj.Sort(comparer); + pictureBoxCollection.Image = obj.ShowTractors(); + } } } diff --git a/RPP_FirstLaba_Tractor/RPP_FirstLaba_Tractor/SetGeneric.cs b/RPP_FirstLaba_Tractor/RPP_FirstLaba_Tractor/SetGeneric.cs index 2996fd2..bb9e0d7 100644 --- a/RPP_FirstLaba_Tractor/RPP_FirstLaba_Tractor/SetGeneric.cs +++ b/RPP_FirstLaba_Tractor/RPP_FirstLaba_Tractor/SetGeneric.cs @@ -33,16 +33,20 @@ namespace ProjectTractor.Generics _places = new List(count); } /// + /// Сортировка набора объектов + /// + /// + public void SortSet(IComparer comparer) => _places.Sort(comparer); + /// /// Добавление объекта в набор /// /// Добавляемый трактор /// - public bool Insert(T tractor) + public void Insert(T tractor, IEqualityComparer? equal = null) { if (_places.Count == _maxCount) throw new StorageOverflowException(_maxCount); - Insert(tractor, 0); - return true; + Insert(tractor, 0, equal); } /// /// Добавление объекта в набор на конкретную позицию @@ -50,12 +54,17 @@ namespace ProjectTractor.Generics /// Добавляемый автомобиль /// Позиция /// - public void Insert(T tractor, int position) + public void Insert(T tractor, int position, IEqualityComparer? equal = null) { if (_places.Count == _maxCount) throw new StorageOverflowException(_maxCount); if (!(position >= 0 && position <= Count)) throw new Exception("Неверная позиция для вставки"); + if (equal != null) + { + if (_places.Contains(tractor, equal)) + throw new ArgumentException(nameof(tractor)); + } _places.Insert(position, tractor); } /// diff --git a/RPP_FirstLaba_Tractor/RPP_FirstLaba_Tractor/TractorCompareByColor.cs b/RPP_FirstLaba_Tractor/RPP_FirstLaba_Tractor/TractorCompareByColor.cs new file mode 100644 index 0000000..832f417 --- /dev/null +++ b/RPP_FirstLaba_Tractor/RPP_FirstLaba_Tractor/TractorCompareByColor.cs @@ -0,0 +1,34 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using ProjectTractor.DrawningObjects; + +namespace ProjectTractor.Generics +{ + internal class TractorCompareByColor : IComparer + { + public int Compare(DrawningTractor? x, DrawningTractor? y) + { + if (x == null || x.EntityTractor == null) + throw new ArgumentNullException(nameof(x)); + + if (y == null || y.EntityTractor == null) + { + throw new ArgumentNullException(nameof(y)); + } + + if (x.EntityTractor.BodyColor.Name != y.EntityTractor.BodyColor.Name) + { + return x.EntityTractor.BodyColor.Name.CompareTo(y.EntityTractor.BodyColor.Name); + } + + var speedCompare = x.EntityTractor.Speed.CompareTo(y.EntityTractor.Speed); + if (speedCompare != 0) + return speedCompare; + + return x.EntityTractor.Weight.CompareTo(y.EntityTractor.Weight); + } + } +} \ No newline at end of file diff --git a/RPP_FirstLaba_Tractor/RPP_FirstLaba_Tractor/TractorCompareByType.cs b/RPP_FirstLaba_Tractor/RPP_FirstLaba_Tractor/TractorCompareByType.cs new file mode 100644 index 0000000..b048012 --- /dev/null +++ b/RPP_FirstLaba_Tractor/RPP_FirstLaba_Tractor/TractorCompareByType.cs @@ -0,0 +1,35 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using ProjectTractor.DrawningObjects; + +namespace ProjectTractor.Generics +{ + internal class TractorCompareByType : IComparer + { + public int Compare(DrawningTractor? x, DrawningTractor? y) + { + if (x == null || x.EntityTractor == null) + { + throw new ArgumentNullException(nameof(x)); + } + if (y == null || y.EntityTractor == null) + { + throw new ArgumentNullException(nameof(y)); + } + if (x.GetType().Name != y.GetType().Name) + { + return x.GetType().Name.CompareTo(y.GetType().Name); + } + var speedCompare = + x.EntityTractor.Speed.CompareTo(y.EntityTractor.Speed); + if (speedCompare != 0) + { + return speedCompare; + } + return x.EntityTractor.Weight.CompareTo(y.EntityTractor.Weight); + } + } +} diff --git a/RPP_FirstLaba_Tractor/RPP_FirstLaba_Tractor/TractorsCollectionInfo.cs b/RPP_FirstLaba_Tractor/RPP_FirstLaba_Tractor/TractorsCollectionInfo.cs new file mode 100644 index 0000000..0df4ef8 --- /dev/null +++ b/RPP_FirstLaba_Tractor/RPP_FirstLaba_Tractor/TractorsCollectionInfo.cs @@ -0,0 +1,31 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + + +namespace ProjectTractor.Generics +{ + internal class TractorsCollectionInfo : IEquatable + { + public string Name { get; private set; } + public string Description { get; private set; } + public TractorsCollectionInfo(string name, string description) + { + Name = name; + Description = description; + } + public bool Equals(TractorsCollectionInfo? other) + { + if (Name == other?.Name) + return true; + return false; + } + public override int GetHashCode() + { + return this.Name.GetHashCode(); + } + } +} + diff --git a/RPP_FirstLaba_Tractor/RPP_FirstLaba_Tractor/TractorsGenericCollection.cs b/RPP_FirstLaba_Tractor/RPP_FirstLaba_Tractor/TractorsGenericCollection.cs index ba1ca31..a290dd0 100644 --- a/RPP_FirstLaba_Tractor/RPP_FirstLaba_Tractor/TractorsGenericCollection.cs +++ b/RPP_FirstLaba_Tractor/RPP_FirstLaba_Tractor/TractorsGenericCollection.cs @@ -65,11 +65,10 @@ namespace ProjectTractor.Generics public static bool operator +(TractorsGenericCollection collect, T? obj) { - if (obj == null) - { + if (obj == null || collect == null) return false; - } - return collect?._collection.Insert(obj) ?? false; + collect?._collection.Insert(obj, new DrawningTractorEqutables()); + return true; } /// /// Перегрузка оператора вычитания @@ -151,6 +150,13 @@ namespace ProjectTractor.Generics } } + /// + /// Сортировка + /// + /// + public void Sort(IComparer comparer) => + _collection.SortSet(comparer); + } } diff --git a/RPP_FirstLaba_Tractor/RPP_FirstLaba_Tractor/TractorsGenericStorage.cs b/RPP_FirstLaba_Tractor/RPP_FirstLaba_Tractor/TractorsGenericStorage.cs index 45f3882..ecf62a1 100644 --- a/RPP_FirstLaba_Tractor/RPP_FirstLaba_Tractor/TractorsGenericStorage.cs +++ b/RPP_FirstLaba_Tractor/RPP_FirstLaba_Tractor/TractorsGenericStorage.cs @@ -18,11 +18,11 @@ namespace ProjectTractor /// /// Словарь (хранилище) /// - readonly Dictionary> _tractorStorages; + readonly Dictionary> _tractorStorages; /// /// Возвращение списка названий наборов /// - public List Keys => _tractorStorages.Keys.ToList(); + public List Keys => _tractorStorages.Keys.ToList(); /// /// Ширина окна отрисовки /// @@ -50,7 +50,7 @@ namespace ProjectTractor /// public TractorsGenericStorage(int pictureWidth, int pictureHeight) { - _tractorStorages = new Dictionary>(); _pictureWidth = pictureWidth; _pictureHeight = pictureHeight; @@ -61,19 +61,8 @@ namespace ProjectTractor /// Название набора public void AddSet(string name) { - try - { - if (_tractorStorages.ContainsKey(name)) - throw new CollectionCreationErrorException(name); - - _tractorStorages.Add(name, - new TractorsGenericCollection(_pictureWidth, _pictureHeight)); - } - catch - { - throw new CollectionCreationErrorException(name); - } + _tractorStorages.Add(new TractorsCollectionInfo(name, string.Empty), new TractorsGenericCollection(_pictureWidth, _pictureHeight)); } /// /// Удаление набора @@ -81,9 +70,9 @@ namespace ProjectTractor /// Название набора public void DelSet(string name) { - if (!_tractorStorages.ContainsKey(name)) + if (!_tractorStorages.ContainsKey(new TractorsCollectionInfo(name, string.Empty))) return; - _tractorStorages.Remove(name); + _tractorStorages.Remove(new TractorsCollectionInfo(name, string.Empty)); } /// /// Доступ к набору @@ -95,8 +84,9 @@ namespace ProjectTractor { get { - if (_tractorStorages.ContainsKey(ind)) - return _tractorStorages[ind]; + TractorsCollectionInfo indObj = new TractorsCollectionInfo(ind, string.Empty); + if (_tractorStorages.ContainsKey(indObj)) + return _tractorStorages[indObj]; return null; } } @@ -106,14 +96,14 @@ namespace ProjectTractor /// /// Путь и имя файла /// true - сохранение прошло успешно, false - ошибка при сохранении данных - public bool SaveData(string filename) + public void SaveData(string filename) { if (File.Exists(filename)) { File.Delete(filename); } StringBuilder data = new(); - foreach (KeyValuePair> record in _tractorStorages) { StringBuilder records = new(); @@ -121,40 +111,40 @@ namespace ProjectTractor { records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}"); } - data.AppendLine($"{record.Key}{_separatorForKeyValue}{records}"); + data.AppendLine($"{record.Key.Name}{_separatorForKeyValue}{records}"); } if (data.Length == 0) { - throw new Exception("Невалиданя операция, нет данных для сохранения"); + throw new IOException("Невалидная операция, нет данных для сохранения"); + } using (StreamWriter streamWriter = new(filename)) { - streamWriter.WriteLine($"TractorStorage{Environment.NewLine}{data}"); + streamWriter.WriteLine($"TractorStorages{Environment.NewLine}{data}"); } - return true; } /// /// Загрузка информации по автомобилям в хранилище из файла /// /// Путь и имя файла // true - загрузка прошла успешно, false - ошибка при загрузке данных - public bool LoadData(string filename) + public void LoadData(string filename) { if (!File.Exists(filename)) { - throw new Exception("Файл не найден"); + throw new IOException("Файл не найден"); + } using (StreamReader streamReader = new(filename)) { string str = streamReader.ReadLine(); - string[] strings = str.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); + var strings = str.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); if (strings == null || strings.Length == 0) { throw new IOException("Нет данных для загрузки"); } - if (!strings[0].StartsWith("TractorStorage")) + if (!strings[0].StartsWith("BusStorages")) { - //если нет такой записи, то это не те данные throw new IOException("Неверный формат данных"); } _tractorStorages.Clear(); @@ -170,20 +160,19 @@ namespace ProjectTractor string[] set = record[1].Split(_separatorRecords, StringSplitOptions.RemoveEmptyEntries); foreach (string elem in set) { - DrawningTractor? tractor = elem?.CreateDrawningTractor(_separatorForObject, _pictureWidth, _pictureHeight); - if (tractor != null) + DrawningTractor? bus = elem?.CreateDrawningTractor(_separatorForObject, _pictureWidth, _pictureHeight); + if (bus != null) { - if (!(collection + tractor)) + if (!(collection + bus)) { - throw new ArgumentNullException("Ошибка добавления в коллекцию"); + throw new IOException("Ошибка добавления в коллекцию"); } } } - _tractorStorages.Add(record[0], collection); + _tractorStorages.Add(new TractorsCollectionInfo(record[0], string.Empty), collection); str = streamReader.ReadLine(); } while (str != null); } - return true; } } }