From 733bc788b631ae77ad62cef6a6eb5c24d698e128 Mon Sep 17 00:00:00 2001 From: Tonb73 Date: Sat, 11 May 2024 11:55:00 +0300 Subject: [PATCH 1/6] =?UTF-8?q?=D0=A1=D0=B4=D0=B5=D0=BB=D0=B0=D0=BB=20?= =?UTF-8?q?=D1=81=D0=BE=D1=80=D1=82=D0=B8=D1=80=D0=BE=D0=B2=D0=BA=D1=83=20?= =?UTF-8?q?=D0=B2=20=D0=BA=D0=BE=D0=BB=D0=BB=D0=B5=D0=BA=D1=86=D0=B8=D1=8F?= =?UTF-8?q?=20=D0=B8=20=D0=B4=D0=BE=D1=88=D0=B5=D0=BB=20=D0=B4=D0=BE=2011?= =?UTF-8?q?=20=D0=BC=D0=B8=D0=BD=D1=83=D1=82=D1=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../AbstractCompany.cs | 2 +- .../ICollectionGenericObjects.cs | 26 ++++++--- .../ListGenericObjects.cs | 14 ++++- .../MassiveGenericObjects.cs | 13 ++++- .../Drawnings/DrawingLocomotiveEqutables.cs | 55 +++++++++++++++++++ .../DrawningLocomotiveCompareByColor.cs | 20 +++++++ .../DrawninglocomotiveCompareByType.cs | 36 ++++++++++++ 7 files changed, 152 insertions(+), 14 deletions(-) create mode 100644 ProjectElectricLocomotive/Drawnings/DrawingLocomotiveEqutables.cs create mode 100644 ProjectElectricLocomotive/Drawnings/DrawningLocomotiveCompareByColor.cs create mode 100644 ProjectElectricLocomotive/Drawnings/DrawninglocomotiveCompareByType.cs diff --git a/ProjectElectricLocomotive/CollectionGenericObjects/AbstractCompany.cs b/ProjectElectricLocomotive/CollectionGenericObjects/AbstractCompany.cs index 0022d60..f8b7406 100644 --- a/ProjectElectricLocomotive/CollectionGenericObjects/AbstractCompany.cs +++ b/ProjectElectricLocomotive/CollectionGenericObjects/AbstractCompany.cs @@ -62,7 +62,7 @@ public abstract class AbstractCompany public static int operator +(AbstractCompany company, DrawningLocomotive locomotive) { - return company._collection.Insert(locomotive); + return company._collection.Insert(locomotive, new DrawiningLocomotiveEqutables()) ?? false; } /// /// Перегрузка оператора удаления для класса diff --git a/ProjectElectricLocomotive/CollectionGenericObjects/ICollectionGenericObjects.cs b/ProjectElectricLocomotive/CollectionGenericObjects/ICollectionGenericObjects.cs index f82973b..9ef401a 100644 --- a/ProjectElectricLocomotive/CollectionGenericObjects/ICollectionGenericObjects.cs +++ b/ProjectElectricLocomotive/CollectionGenericObjects/ICollectionGenericObjects.cs @@ -27,22 +27,23 @@ public interface ICollectionGenericObjects /// /// Добавляемый объект /// true - вставка прошла удачно, false - вставка не удалась - int Insert(T obj); - + /// + /// Добавление объекта в коллекцию + /// + /// Добавляемый объект + /// Cравнение двух объектов + /// true - вставка прошла удачно, false - вставка не удалась + int Insert(T obj, IEqualityComparer? comparer = null); /// /// Добавление объекта в коллекцию на конкретную позицию /// /// Добавляемый объект /// Позиция + /// Cравнение двух объектов /// true - вставка прошла удачно, false - вставка не удалась -int Insert(T obj, int position); + int Insert(T obj, int position, IEqualityComparer? comparer = null); - /// - /// Удаление объекта из коллекции с конкретной позиции - /// - /// Позиция - /// true - удаление прошло удачно, false - удаление не удалось -T Remove(int position); + T Remove(int position); /// /// Получение объекта по позиции /// @@ -60,4 +61,11 @@ T Remove(int position); /// /// Поэлементый вывод элементов коллекции IEnumerable GetItems(); + + /// + /// Сортировка коллекции + /// + /// Сравнитель объектов + void CollectionSort(IComparer comparer); + } diff --git a/ProjectElectricLocomotive/CollectionGenericObjects/ListGenericObjects.cs b/ProjectElectricLocomotive/CollectionGenericObjects/ListGenericObjects.cs index 0e4148e..0ea64ee 100644 --- a/ProjectElectricLocomotive/CollectionGenericObjects/ListGenericObjects.cs +++ b/ProjectElectricLocomotive/CollectionGenericObjects/ListGenericObjects.cs @@ -55,21 +55,25 @@ namespace ProjectElectricLocomotive.CollectionGenericObjects return _collection[position]; } - public int Insert(T obj) + public int Insert(T obj, IEqualityComparer? comparer = null) { // выброс ошибки если переполнение + //выброс ошибки если такой объект уже есть в коллекции + if (Count == _maxCount) throw new CollectionOverflowException(Count); _collection.Add(obj); 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(Count); @@ -98,5 +102,11 @@ namespace ProjectElectricLocomotive.CollectionGenericObjects yield return _collection[i]; } } + + public void CollectionSort(IComparer comparer) + { + _collection.Sort(comparer); + throw new NotImplementedException(); + } } } diff --git a/ProjectElectricLocomotive/CollectionGenericObjects/MassiveGenericObjects.cs b/ProjectElectricLocomotive/CollectionGenericObjects/MassiveGenericObjects.cs index 44925ab..0cb1f62 100644 --- a/ProjectElectricLocomotive/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/ProjectElectricLocomotive/CollectionGenericObjects/MassiveGenericObjects.cs @@ -56,11 +56,13 @@ namespace ProjectElectricLocomotive.CollectionGenericObjects if (_collection[position] == null) throw new ObjectNotFoundException(position); return _collection[position]; } - public int Insert(T obj) + public int Insert(T obj, IEqualityComparer? comparer = null) { // вставка в свободное место набора // выброс ошибки, если переполнение //выброс ошибки, если выход за границы массива + //выброс ошибки если такой объект уже есть в коллекции + for (int i = 0; i < Count; i++) { if (_collection[i] == null) @@ -72,7 +74,7 @@ namespace ProjectElectricLocomotive.CollectionGenericObjects throw new CollectionOverflowException(Count); } - public int Insert(T obj, int position) + public int Insert(T obj, int position, IEqualityComparer? comparer = null) { // проверка позиции // проверка, что элемент массива по этой позиции пустой, если нет, то @@ -80,6 +82,7 @@ namespace ProjectElectricLocomotive.CollectionGenericObjects // вставка //выброс ошибки, если переполнение //выброс ошибки, если выход за границы массива + //выброс ошибки если такой объект уже есть в коллекции if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position); if (_collection[position] == null) @@ -128,5 +131,11 @@ namespace ProjectElectricLocomotive.CollectionGenericObjects yield return _collection[i]; } } + + public void CollectionSort(IComparer comparer) + { + Array.Sort(_collection, comparer); + throw new NotImplementedException(); + } } } diff --git a/ProjectElectricLocomotive/Drawnings/DrawingLocomotiveEqutables.cs b/ProjectElectricLocomotive/Drawnings/DrawingLocomotiveEqutables.cs new file mode 100644 index 0000000..8693a10 --- /dev/null +++ b/ProjectElectricLocomotive/Drawnings/DrawingLocomotiveEqutables.cs @@ -0,0 +1,55 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectElectricLocomotive.Drawnings; + +/// +/// Реализация сравнения двух объектов класса-прорисовки +/// +public class DrawiningLocomotiveEqutables : IEqualityComparer +{ + public bool Equals(DrawningLocomotive? x, DrawningLocomotive? y) + { + if (x == null || x.EntityLocomotive == null) + { + return false; + } + if (y == null || y.EntityLocomotive == null) + { + return false; + } + if (x.GetType().Name != y.GetType().Name) + { + return false; + } + if (x.EntityLocomotive.Speed != y.EntityLocomotive.Speed) + { + return false; + } + if (x.EntityLocomotive.Weight != y.EntityLocomotive.Weight) + { + return false; + } + if (x.EntityLocomotive.BodyColor != y.EntityLocomotive.BodyColor) + { + return false; + } + if (x is DrawningElectricLocomotive && y is DrawningElectricLocomotive) + { + + + + // TODO доделать логику сравнения дополнительных параметров + } + return true; + } + public int GetHashCode([DisallowNull] DrawningLocomotive obj) + { + return obj.GetHashCode(); + } +} + diff --git a/ProjectElectricLocomotive/Drawnings/DrawningLocomotiveCompareByColor.cs b/ProjectElectricLocomotive/Drawnings/DrawningLocomotiveCompareByColor.cs new file mode 100644 index 0000000..686342d --- /dev/null +++ b/ProjectElectricLocomotive/Drawnings/DrawningLocomotiveCompareByColor.cs @@ -0,0 +1,20 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectElectricLocomotive.Drawnings +{ + /// +/// Сравнение по цвету, скорости, весу +/// +public class DrawningCarCompareByColor : IComparer +{ +public int Compare(DrawningLocomotive? x, DrawningLocomotive? y) +{ +// TODO прописать логику сравения по цветам, скорости, весу +throw new NotImplementedException(); +} +} +} diff --git a/ProjectElectricLocomotive/Drawnings/DrawninglocomotiveCompareByType.cs b/ProjectElectricLocomotive/Drawnings/DrawninglocomotiveCompareByType.cs new file mode 100644 index 0000000..40f93a3 --- /dev/null +++ b/ProjectElectricLocomotive/Drawnings/DrawninglocomotiveCompareByType.cs @@ -0,0 +1,36 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectElectricLocomotive.Drawnings; + +/// +/// Сравнение по типу, скорости, весу +/// +public class DrawningCarCompareByType : IComparer +{ + public int Compare(DrawningLocomotive? x, DrawningLocomotive? y) + { + if (x == null || x.EntityLocomotive == null) + { + return -1; + } + if (y == null || y.EntityLocomotive == null) + { + return 1; + } + if (x.GetType().Name != y.GetType().Name) + { + return x.GetType().Name.CompareTo(y.GetType().Name); + } + var speedCompare = x.EntityLocomotive.Speed.CompareTo(y.EntityLocomotive.Speed); + if (speedCompare != 0) + { + return speedCompare; + } + return x.EntityLocomotive.Weight.CompareTo(y.EntityLocomotive.Weight); + } +} + -- 2.25.1 From 289bcf43c78cef1e8aa1575c251dac22c5878997 Mon Sep 17 00:00:00 2001 From: Tonb73 Date: Sat, 11 May 2024 12:20:57 +0300 Subject: [PATCH 2/6] =?UTF-8?q?=D0=9F=D0=BE=D1=81=D0=BB=D0=B5=20=D0=B2?= =?UTF-8?q?=D0=B8=D0=B4=D0=B5=D0=BE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../AbstractCompany.cs | 6 ++ .../CollectionInfo.cs | 78 +++++++++++++++++ .../StorageCollection.cs | 86 +++++++++---------- .../DrawningLocomotiveCompareByColor.cs | 2 +- .../DrawninglocomotiveCompareByType.cs | 2 +- .../FormLocomotiveCollection.Designer.cs | 34 +++++++- .../FormLocomotiveCollection.cs | 37 +++++++- 7 files changed, 194 insertions(+), 51 deletions(-) create mode 100644 ProjectElectricLocomotive/CollectionGenericObjects/CollectionInfo.cs diff --git a/ProjectElectricLocomotive/CollectionGenericObjects/AbstractCompany.cs b/ProjectElectricLocomotive/CollectionGenericObjects/AbstractCompany.cs index f8b7406..1e6b4d2 100644 --- a/ProjectElectricLocomotive/CollectionGenericObjects/AbstractCompany.cs +++ b/ProjectElectricLocomotive/CollectionGenericObjects/AbstractCompany.cs @@ -106,6 +106,12 @@ public abstract class AbstractCompany return bitmap; } + /// + /// Сортировка + /// + /// Сравнитель объектов + public void Sort(IComparer comparer) => _collection?.CollectionSort(comparer); + /// /// Вывод заднего фона /// diff --git a/ProjectElectricLocomotive/CollectionGenericObjects/CollectionInfo.cs b/ProjectElectricLocomotive/CollectionGenericObjects/CollectionInfo.cs new file mode 100644 index 0000000..9aec61a --- /dev/null +++ b/ProjectElectricLocomotive/CollectionGenericObjects/CollectionInfo.cs @@ -0,0 +1,78 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectElectricLocomotive.CollectionGenericObjects +{ + /// + /// Класс, хранящиий информацию по коллекции + /// + public class CollectionInfo : IEquatable + { + /// + /// Название + /// + public string Name { get; private set; } + /// + /// Тип + /// + public CollectionType CollectionType { get; private set; } + /// + /// Описание + /// + public string Description { get; private set; } + /// + /// Разделитель для записи информации по объекту в файл + /// + private static readonly string _separator = "-"; + /// + /// Конструктор + /// + /// /// Название + /// Тип + /// Описание + public CollectionInfo(string name, CollectionType collectionType, string + description) + { + Name = name; + CollectionType = collectionType; + Description = description; + } + /// + /// Создание объекта из строки + /// + /// Строка + /// Объект или null + public static CollectionInfo? GetCollectionInfo(string data) + { + string[] strs = data.Split(_separator, + StringSplitOptions.RemoveEmptyEntries); + if (strs.Length < 1 || strs.Length > 3) + { + return null; + } + return new CollectionInfo(strs[0], + (CollectionType)Enum.Parse(typeof(CollectionType), strs[1]), strs.Length > 2 ? + strs[2] : string.Empty); + } + public override string ToString() + { + return Name + _separator + CollectionType + _separator + Description; + } + public bool Equals(CollectionInfo? other) + { + return Name == other?.Name; + } + public override bool Equals(object? obj) + { + return Equals(obj as CollectionInfo); + } + public override int GetHashCode() + { + return Name.GetHashCode(); + } + + } +} diff --git a/ProjectElectricLocomotive/CollectionGenericObjects/StorageCollection.cs b/ProjectElectricLocomotive/CollectionGenericObjects/StorageCollection.cs index e0a0baa..1aed8cf 100644 --- a/ProjectElectricLocomotive/CollectionGenericObjects/StorageCollection.cs +++ b/ProjectElectricLocomotive/CollectionGenericObjects/StorageCollection.cs @@ -19,17 +19,17 @@ where T : DrawningLocomotive /// /// Словарь (хранилище) с коллекциями /// - readonly Dictionary> _storages; + readonly Dictionary> _storages; /// /// Возвращение списка названий коллекций /// - public List Keys => _storages.Keys.ToList(); + public List Keys => _storages.Keys.ToList(); /// /// Конструктор /// public StorageCollection() { - _storages = new Dictionary>(); + _storages = new Dictionary>(); } /// /// Добавление коллекции в хранилище @@ -101,51 +101,49 @@ where T : DrawningLocomotive /// /// Путь и имя файла /// true - сохранение прошло успешно, false - ошибка при сохранении данных + /// + /// Сохранение информации по автомобилям в хранилище в файл + /// + /// Путь и имя файла public void SaveData(string filename) { + if (_storages.Count == 0) { - if (_storages.Count == 0) + throw new Exception("В хранилище отсутствуют коллекции для сохранения"); + } + if (File.Exists(filename)) + { + File.Delete(filename); + } + StringBuilder sb = new(); + sb.Append(_collectionKey); + foreach (KeyValuePair> + value in _storages) + { + sb.Append(Environment.NewLine); + // не сохраняем пустые коллекции + if (value.Value.Count == 0) { - throw new Exception("В хранилище отсутствуют коллекции для сохранения"); - + continue; } - if (File.Exists(filename)) + sb.Append(value.Key); + sb.Append(_separatorForKeyValue); + sb.Append(value.Value.MaxCount); + sb.Append(_separatorForKeyValue); + foreach (T? item in value.Value.GetItems()) { - File.Delete(filename); - } - using (StreamWriter writer = new StreamWriter(filename)) - { - writer.Write(_collectionKey); - foreach (KeyValuePair> value in _storages) + string data = item?.GetDataForSave() ?? string.Empty; + if (string.IsNullOrEmpty(data)) { - StringBuilder sb = new(); // построитель строк - sb.Append(Environment.NewLine); - // не сохраняем пустые коллекции - if (value.Value.Count == 0) - { - continue; - } - sb.Append(value.Key); - sb.Append(_separatorForKeyValue); - sb.Append(value.Value.GetCollectionType); - sb.Append(_separatorForKeyValue); - sb.Append(value.Value.MaxCount); - sb.Append(_separatorForKeyValue); - foreach (T? item in value.Value.GetItems()) - { - string data = item?.GetDataForSave() ?? string.Empty; - if (string.IsNullOrEmpty(data)) - { - continue; - } - sb.Append(data); - sb.Append(_separatorItems); - } - writer.Write(sb); + continue; } - + sb.Append(data); + sb.Append(_separatorItems); } } + using FileStream fs = new(filename, FileMode.Create); + byte[] info = new UTF8Encoding(true).GetBytes(sb.ToString()); + fs.Write(info, 0, info.Length); } /// @@ -177,26 +175,26 @@ where T : DrawningLocomotive while ((strs = fs.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); if (collection == null) { throw new Exception("Не удалось создать коллекцию"); } - collection.MaxCount = Convert.ToInt32(record[2]); - string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); + collection.MaxCount = Convert.ToInt32(record[1]); + string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); foreach (string elem in set) { - if (elem?.CreateDrawningLocomotive() is T truck) + if (elem?.CreateDrawningLocomotive() is T locomotive) { try { - if (collection.Insert(truck) == -1) + if (collection.Insert(locomotive) == -1) { throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]); } diff --git a/ProjectElectricLocomotive/Drawnings/DrawningLocomotiveCompareByColor.cs b/ProjectElectricLocomotive/Drawnings/DrawningLocomotiveCompareByColor.cs index 686342d..733560d 100644 --- a/ProjectElectricLocomotive/Drawnings/DrawningLocomotiveCompareByColor.cs +++ b/ProjectElectricLocomotive/Drawnings/DrawningLocomotiveCompareByColor.cs @@ -9,7 +9,7 @@ namespace ProjectElectricLocomotive.Drawnings /// /// Сравнение по цвету, скорости, весу /// -public class DrawningCarCompareByColor : IComparer +public class DrawningLocomotiveCompareByColor : IComparer { public int Compare(DrawningLocomotive? x, DrawningLocomotive? y) { diff --git a/ProjectElectricLocomotive/Drawnings/DrawninglocomotiveCompareByType.cs b/ProjectElectricLocomotive/Drawnings/DrawninglocomotiveCompareByType.cs index 40f93a3..77a58b2 100644 --- a/ProjectElectricLocomotive/Drawnings/DrawninglocomotiveCompareByType.cs +++ b/ProjectElectricLocomotive/Drawnings/DrawninglocomotiveCompareByType.cs @@ -9,7 +9,7 @@ namespace ProjectElectricLocomotive.Drawnings; /// /// Сравнение по типу, скорости, весу /// -public class DrawningCarCompareByType : IComparer +public class DrawningLocomotiveCompareByType : IComparer { public int Compare(DrawningLocomotive? x, DrawningLocomotive? y) { diff --git a/ProjectElectricLocomotive/FormLocomotiveCollection.Designer.cs b/ProjectElectricLocomotive/FormLocomotiveCollection.Designer.cs index a0d983a..19804a7 100644 --- a/ProjectElectricLocomotive/FormLocomotiveCollection.Designer.cs +++ b/ProjectElectricLocomotive/FormLocomotiveCollection.Designer.cs @@ -52,6 +52,8 @@ LoadToolStripMenuItem = new ToolStripMenuItem(); openFileDialog = new OpenFileDialog(); saveFileDialog = new SaveFileDialog(); + buttonSortByColor = new Button(); + buttonSortByType = new Button(); groupBoxTools.SuspendLayout(); panelCompanyTools.SuspendLayout(); panelStorage.SuspendLayout(); @@ -76,7 +78,9 @@ // // panelCompanyTools // + panelCompanyTools.Controls.Add(buttonSortByColor); panelCompanyTools.Controls.Add(buttonAddLocomotive); + panelCompanyTools.Controls.Add(buttonSortByType); panelCompanyTools.Controls.Add(maskedTextBox); panelCompanyTools.Controls.Add(buttonDelLocomotive); panelCompanyTools.Controls.Add(buttonRefresh); @@ -99,7 +103,7 @@ // // maskedTextBox // - maskedTextBox.Location = new Point(12, 146); + maskedTextBox.Location = new Point(12, 82); maskedTextBox.Mask = "00"; maskedTextBox.Name = "maskedTextBox"; maskedTextBox.Size = new Size(193, 31); @@ -108,7 +112,7 @@ // // buttonDelLocomotive // - buttonDelLocomotive.Location = new Point(12, 183); + buttonDelLocomotive.Location = new Point(12, 119); buttonDelLocomotive.Name = "buttonDelLocomotive"; buttonDelLocomotive.Size = new Size(193, 63); buttonDelLocomotive.TabIndex = 5; @@ -118,7 +122,7 @@ // // buttonRefresh // - buttonRefresh.Location = new Point(12, 297); + buttonRefresh.Location = new Point(12, 233); buttonRefresh.Name = "buttonRefresh"; buttonRefresh.Size = new Size(193, 39); buttonRefresh.TabIndex = 7; @@ -128,7 +132,7 @@ // // buttonGoToCheck // - buttonGoToCheck.Location = new Point(12, 252); + buttonGoToCheck.Location = new Point(12, 188); buttonGoToCheck.Name = "buttonGoToCheck"; buttonGoToCheck.Size = new Size(193, 39); buttonGoToCheck.TabIndex = 6; @@ -288,6 +292,26 @@ // saveFileDialog.Filter = "txt file | *.txt"; // + // buttonSortByColor + // + buttonSortByColor.Location = new Point(12, 323); + buttonSortByColor.Name = "buttonSortByColor"; + buttonSortByColor.Size = new Size(193, 37); + buttonSortByColor.TabIndex = 9; + buttonSortByColor.Text = "Сортировка по цвет"; + buttonSortByColor.UseVisualStyleBackColor = true; + buttonSortByColor.Click += buttonSortByColor_Click; + // + // buttonSortByType + // + buttonSortByType.Location = new Point(12, 278); + buttonSortByType.Name = "buttonSortByType"; + buttonSortByType.Size = new Size(193, 39); + buttonSortByType.TabIndex = 8; + buttonSortByType.Text = "Сортировка по типу"; + buttonSortByType.UseVisualStyleBackColor = true; + buttonSortByType.Click += buttonSortByType_Click; + // // FormLocomotiveCollection // AutoScaleDimensions = new SizeF(10F, 25F); @@ -338,5 +362,7 @@ private ToolStripMenuItem LoadToolStripMenuItem; private OpenFileDialog openFileDialog; private SaveFileDialog saveFileDialog; + private Button buttonSortByColor; + private Button buttonSortByType; } } \ No newline at end of file diff --git a/ProjectElectricLocomotive/FormLocomotiveCollection.cs b/ProjectElectricLocomotive/FormLocomotiveCollection.cs index ee29efa..6c1b65d 100644 --- a/ProjectElectricLocomotive/FormLocomotiveCollection.cs +++ b/ProjectElectricLocomotive/FormLocomotiveCollection.cs @@ -31,7 +31,7 @@ public partial class FormLocomotiveCollection : Form /// /// Логер /// - private readonly ILogger _logger; + private readonly ILogger _logger; /// /// Компания @@ -352,4 +352,39 @@ public partial class FormLocomotiveCollection : Form } } } + + /// + /// Сортировка по цвету + /// + /// + /// + private void buttonSortByColor_Click(object sender, EventArgs e) + { + CompareLocomotives(new DrawningLocomotiveCompareByColor()); + } + + /// + /// Сортировка по типу + /// + /// + /// + private void buttonSortByType_Click(object sender, EventArgs e) + { + CompareLocomotives(new DrawningLocomotiveCompareByType()); + } + + /// + /// Сортировка по сравнителю + /// + /// Сравнитель объектов + private void CompareLocomotives(IComparer comparer) + { + if (_company == null) + { + return; + } + _company.Sort(comparer); + pictureBox.Image = _company.Show(); + } + } -- 2.25.1 From bf21edec3e4c3c2a81023d81bd84a89583a68775 Mon Sep 17 00:00:00 2001 From: Tonb73 Date: Sun, 12 May 2024 10:58:04 +0300 Subject: [PATCH 3/6] =?UTF-8?q?=D0=A0=D0=B0=D0=B1=D0=BE=D1=82=D0=B0=D0=B5?= =?UTF-8?q?=D0=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../AbstractCompany.cs | 3 +- .../ListGenericObjects.cs | 23 +++++++++- .../MassiveGenericObjects.cs | 23 +++++++++- .../StorageCollection.cs | 22 +++++---- .../Drawnings/DrawingLocomotiveEqutables.cs | 21 +++++++-- .../DrawningLocomotiveCompareByColor.cs | 45 ++++++++++++++----- .../CollectionDuplicateException.cs | 21 +++++++++ .../Exceptions/DrawningEqutablesException.cs | 20 +++++++++ 8 files changed, 150 insertions(+), 28 deletions(-) create mode 100644 ProjectElectricLocomotive/Exceptions/CollectionDuplicateException.cs create mode 100644 ProjectElectricLocomotive/Exceptions/DrawningEqutablesException.cs diff --git a/ProjectElectricLocomotive/CollectionGenericObjects/AbstractCompany.cs b/ProjectElectricLocomotive/CollectionGenericObjects/AbstractCompany.cs index 1e6b4d2..92b97c9 100644 --- a/ProjectElectricLocomotive/CollectionGenericObjects/AbstractCompany.cs +++ b/ProjectElectricLocomotive/CollectionGenericObjects/AbstractCompany.cs @@ -1,4 +1,5 @@ using ProjectElectricLocomotive.Drawnings; +using ProjectElectricLocomotive.Exceptions; using System; using System.Collections.Generic; using System.Linq; @@ -62,7 +63,7 @@ public abstract class AbstractCompany public static int operator +(AbstractCompany company, DrawningLocomotive locomotive) { - return company._collection.Insert(locomotive, new DrawiningLocomotiveEqutables()) ?? false; + return company._collection?.Insert(locomotive, new DrawiningLocomotiveEqutables()) ?? throw new DrawningEqutablesException(); } /// /// Перегрузка оператора удаления для класса diff --git a/ProjectElectricLocomotive/CollectionGenericObjects/ListGenericObjects.cs b/ProjectElectricLocomotive/CollectionGenericObjects/ListGenericObjects.cs index 0ea64ee..52bb216 100644 --- a/ProjectElectricLocomotive/CollectionGenericObjects/ListGenericObjects.cs +++ b/ProjectElectricLocomotive/CollectionGenericObjects/ListGenericObjects.cs @@ -60,6 +60,17 @@ namespace ProjectElectricLocomotive.CollectionGenericObjects // выброс ошибки если переполнение //выброс ошибки если такой объект уже есть в коллекции + if(comparer != null) + { + for(int i = 0; i < Count; i++) + { + if (comparer.Equals(_collection[i], obj)) + { + throw new CollectionDuplicateException(obj); + } + } + } + if (Count == _maxCount) throw new CollectionOverflowException(Count); _collection.Add(obj); return Count; @@ -73,6 +84,16 @@ namespace ProjectElectricLocomotive.CollectionGenericObjects // выброс ошибки, если переполнение // выброс ошибки если выход за границу //выброс ошибки если такой объект уже есть в коллекции + if (comparer != null) + { + for (int i = 0; i < Count; i++) + { + if (comparer.Equals(_collection[i], obj)) + { + throw new CollectionDuplicateException(obj); + } + } + } if (Count == _maxCount) throw new CollectionOverflowException(Count); @@ -106,7 +127,7 @@ namespace ProjectElectricLocomotive.CollectionGenericObjects public void CollectionSort(IComparer comparer) { _collection.Sort(comparer); - throw new NotImplementedException(); + // throw new NotImplementedException(); } } } diff --git a/ProjectElectricLocomotive/CollectionGenericObjects/MassiveGenericObjects.cs b/ProjectElectricLocomotive/CollectionGenericObjects/MassiveGenericObjects.cs index 0cb1f62..31198e8 100644 --- a/ProjectElectricLocomotive/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/ProjectElectricLocomotive/CollectionGenericObjects/MassiveGenericObjects.cs @@ -63,6 +63,17 @@ namespace ProjectElectricLocomotive.CollectionGenericObjects //выброс ошибки, если выход за границы массива //выброс ошибки если такой объект уже есть в коллекции + if(comparer != null) + { + for(int i = 0; i < Count; i++) + { + if (comparer.Equals(_collection[i], obj)) + { + throw new CollectionDuplicateException(obj); + } + } + } + for (int i = 0; i < Count; i++) { if (_collection[i] == null) @@ -84,6 +95,16 @@ namespace ProjectElectricLocomotive.CollectionGenericObjects //выброс ошибки, если выход за границы массива //выброс ошибки если такой объект уже есть в коллекции if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position); + if(comparer != null) + { + for(int i = 0; i < Count; i++) + { + if (comparer.Equals(_collection[i], obj)) + { + throw new CollectionDuplicateException(obj); + } + } + } if (_collection[position] == null) { @@ -135,7 +156,7 @@ namespace ProjectElectricLocomotive.CollectionGenericObjects public void CollectionSort(IComparer comparer) { Array.Sort(_collection, comparer); - throw new NotImplementedException(); + // throw new NotImplementedException(); } } } diff --git a/ProjectElectricLocomotive/CollectionGenericObjects/StorageCollection.cs b/ProjectElectricLocomotive/CollectionGenericObjects/StorageCollection.cs index 1aed8cf..88ce44a 100644 --- a/ProjectElectricLocomotive/CollectionGenericObjects/StorageCollection.cs +++ b/ProjectElectricLocomotive/CollectionGenericObjects/StorageCollection.cs @@ -36,20 +36,18 @@ where T : DrawningLocomotive /// /// Название коллекции /// тип коллекции - public void AddCollection(string name, CollectionType collectionType) + public void AddCollection(CollectionInfo collectionInfo) { - if(collectionType != CollectionType.None && !_storages.ContainsKey(name)) { - if(collectionType == CollectionType.List) - { - _storages.Add(name, new ListGenericObjects()); - } - else if (collectionType == CollectionType.Massive) - { - _storages.Add(name, new MassiveGenericObjects()); - } - } // TODO проверка, что name не пустой и нет в словаре записи с таким ключом - // TODO Прописать логику для добавления + // TODO Прописать логику для добавления + if (_storages.ContainsKey(collectionInfo)) throw new CollectionExistsException(collectionInfo); + if (collectionInfo.CollectionType == CollectionType.None) + throw new CollectionNoTypeException("Пустой тип коллекции"); + if (collectionInfo.CollectionType == CollectionType.Massive) + _storages[collectionInfo] = new MassiveGenericObjects(); + else if (collectionInfo.CollectionType == CollectionType.List) + _storages[collectionInfo] = new ListGenericObjects(); + } /// /// Удаление коллекции diff --git a/ProjectElectricLocomotive/Drawnings/DrawingLocomotiveEqutables.cs b/ProjectElectricLocomotive/Drawnings/DrawingLocomotiveEqutables.cs index 8693a10..35aef01 100644 --- a/ProjectElectricLocomotive/Drawnings/DrawingLocomotiveEqutables.cs +++ b/ProjectElectricLocomotive/Drawnings/DrawingLocomotiveEqutables.cs @@ -1,4 +1,5 @@ -using System; +using ProjectElectricLocomotive.Entities; +using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; @@ -40,10 +41,24 @@ public class DrawiningLocomotiveEqutables : IEqualityComparer -/// Сравнение по цвету, скорости, весу -/// -public class DrawningLocomotiveCompareByColor : IComparer -{ -public int Compare(DrawningLocomotive? x, DrawningLocomotive? y) -{ -// TODO прописать логику сравения по цветам, скорости, весу -throw new NotImplementedException(); -} -} + /// Сравнение по цвету, скорости, весу + /// + public class DrawningLocomotiveCompareByColor : IComparer + { + public int Compare(DrawningLocomotive? x, DrawningLocomotive? y) + { + if (x == null && y == null) return 0; + if (x == null || x.EntityLocomotive == null) + { + return 1; + } + + if (y == null || y.EntityLocomotive == null) + { + return -1; + } + + if (ToHex(x.EntityLocomotive.BodyColor) != ToHex(y.EntityLocomotive.BodyColor)) + { + return String.Compare(ToHex(x.EntityLocomotive.BodyColor), ToHex(y.EntityLocomotive.BodyColor), + StringComparison.Ordinal); + } + + var speedCompare = x.EntityLocomotive.Speed.CompareTo(y.EntityLocomotive.Speed); + if (speedCompare != 0) + { + return speedCompare; + } + + return x.EntityLocomotive.Weight.CompareTo(y.EntityLocomotive.Weight); + } + + private static String ToHex(Color c) => $"#{c.R:X2}{c.G:X2}{c.B:X2}"; + } } + diff --git a/ProjectElectricLocomotive/Exceptions/CollectionDuplicateException.cs b/ProjectElectricLocomotive/Exceptions/CollectionDuplicateException.cs new file mode 100644 index 0000000..7ccbcd2 --- /dev/null +++ b/ProjectElectricLocomotive/Exceptions/CollectionDuplicateException.cs @@ -0,0 +1,21 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectElectricLocomotive.Exceptions +{ + public class CollectionDuplicateException : Exception + { + public CollectionDuplicateException(object obj) : base("Объект " + obj + " не является уникальным") { } + public CollectionDuplicateException() : base() { } + public CollectionDuplicateException(string message) : base(message) { } + public CollectionDuplicateException(string message, Exception exception) : + base(message, exception) + { } + protected CollectionDuplicateException(SerializationInfo info, StreamingContext + contex) : base(info, contex) { } + } +} diff --git a/ProjectElectricLocomotive/Exceptions/DrawningEqutablesException.cs b/ProjectElectricLocomotive/Exceptions/DrawningEqutablesException.cs new file mode 100644 index 0000000..f914f47 --- /dev/null +++ b/ProjectElectricLocomotive/Exceptions/DrawningEqutablesException.cs @@ -0,0 +1,20 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectElectricLocomotive.Exceptions +{ + public class DrawningEqutablesException : Exception + { + public DrawningEqutablesException() : base("Оба объекта прорисовки одинаковые") { } + public DrawningEqutablesException(string message) : base(message) { } + public DrawningEqutablesException(string message, Exception exception) : + base(message, exception) + { } + protected DrawningEqutablesException(SerializationInfo info, StreamingContext + contex) : base(info, contex) { } + } +} -- 2.25.1 From 4479e26b20e449d6a995d95436e05c0bade03922 Mon Sep 17 00:00:00 2001 From: Tonb73 Date: Sun, 12 May 2024 11:28:30 +0300 Subject: [PATCH 4/6] =?UTF-8?q?=D0=9D=D1=83,=20=D0=BD=D0=B5=20=D1=80=D0=BE?= =?UTF-8?q?=D0=B1=D0=B8=D1=82=20=D0=BB=D0=BE=D0=BB)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../CollectionInfo.cs | 5 + .../StorageCollection.cs | 111 +++++++++--------- .../Exceptions/CollectionExistsException.cs | 21 ++++ .../Exceptions/CollectionNoInfoException.cs | 20 ++++ .../Exceptions/CollectionNoTypeException.cs | 22 ++++ .../Exceptions/EmptyFileExeption.cs | 21 ++++ .../FormLocomotiveCollection.cs | 68 +++++------ 7 files changed, 180 insertions(+), 88 deletions(-) create mode 100644 ProjectElectricLocomotive/Exceptions/CollectionExistsException.cs create mode 100644 ProjectElectricLocomotive/Exceptions/CollectionNoInfoException.cs create mode 100644 ProjectElectricLocomotive/Exceptions/CollectionNoTypeException.cs create mode 100644 ProjectElectricLocomotive/Exceptions/EmptyFileExeption.cs diff --git a/ProjectElectricLocomotive/CollectionGenericObjects/CollectionInfo.cs b/ProjectElectricLocomotive/CollectionGenericObjects/CollectionInfo.cs index 9aec61a..314d3b0 100644 --- a/ProjectElectricLocomotive/CollectionGenericObjects/CollectionInfo.cs +++ b/ProjectElectricLocomotive/CollectionGenericObjects/CollectionInfo.cs @@ -73,6 +73,11 @@ namespace ProjectElectricLocomotive.CollectionGenericObjects { return Name.GetHashCode(); } + public bool IsEmpty() + { + if (string.IsNullOrEmpty(Name) && CollectionType != CollectionType.None) return true; + return false; + } } } diff --git a/ProjectElectricLocomotive/CollectionGenericObjects/StorageCollection.cs b/ProjectElectricLocomotive/CollectionGenericObjects/StorageCollection.cs index 88ce44a..b2a00c1 100644 --- a/ProjectElectricLocomotive/CollectionGenericObjects/StorageCollection.cs +++ b/ProjectElectricLocomotive/CollectionGenericObjects/StorageCollection.cs @@ -42,7 +42,7 @@ where T : DrawningLocomotive // TODO Прописать логику для добавления if (_storages.ContainsKey(collectionInfo)) throw new CollectionExistsException(collectionInfo); if (collectionInfo.CollectionType == CollectionType.None) - throw new CollectionNoTypeException("Пустой тип коллекции"); + throw new CollectionNoTypeException("Отсутсвует тип коллекции"); if (collectionInfo.CollectionType == CollectionType.Massive) _storages[collectionInfo] = new MassiveGenericObjects(); else if (collectionInfo.CollectionType == CollectionType.List) @@ -53,28 +53,24 @@ where T : DrawningLocomotive /// Удаление коллекции /// /// Название коллекции - public void DelCollection(string name) + public void DelCollection(CollectionInfo collectionInfo) { - if (_storages.ContainsKey(name)) - { - _storages.Remove(name); - } // TODO Прописать логику для удаления коллекции + if (_storages.ContainsKey(collectionInfo)) + _storages.Remove(collectionInfo); } /// /// Доступ к коллекции /// /// Название коллекции /// - public ICollectionGenericObjects? this[string name] + public ICollectionGenericObjects? this[CollectionInfo collectionInfo] { get { - if (_storages.ContainsKey(name)) - { - return _storages[name]; - } // TODO Продумать логику получения объекта + if (_storages.ContainsKey(collectionInfo)) + return _storages[collectionInfo]; return null; } } @@ -107,41 +103,46 @@ where T : DrawningLocomotive { if (_storages.Count == 0) { - throw new Exception("В хранилище отсутствуют коллекции для сохранения"); + throw new EmptyFileExeption(); } + if (File.Exists(filename)) { File.Delete(filename); } - StringBuilder sb = new(); - sb.Append(_collectionKey); - foreach (KeyValuePair> - value in _storages) + + using (StreamWriter writer = new StreamWriter(filename)) { - sb.Append(Environment.NewLine); - // не сохраняем пустые коллекции - if (value.Value.Count == 0) + writer.Write(_collectionKey); + foreach (KeyValuePair> value in _storages) { - continue; - } - sb.Append(value.Key); - sb.Append(_separatorForKeyValue); - sb.Append(value.Value.MaxCount); - sb.Append(_separatorForKeyValue); - foreach (T? item in value.Value.GetItems()) - { - string data = item?.GetDataForSave() ?? string.Empty; - if (string.IsNullOrEmpty(data)) + StringBuilder sb = new(); + sb.Append(Environment.NewLine); + // не сохраняем пустые коллекции + if (value.Value.Count == 0) { continue; } - sb.Append(data); - sb.Append(_separatorItems); + + sb.Append(value.Key); + sb.Append(_separatorForKeyValue); + sb.Append(value.Value.MaxCount); + sb.Append(_separatorForKeyValue); + foreach (T? item in value.Value.GetItems()) + { + string data = item?.GetDataForSave() ?? string.Empty; + if (string.IsNullOrEmpty(data)) + { + continue; + } + + sb.Append(data); + sb.Append(_separatorItems); + } + + writer.Write(sb); } } - using FileStream fs = new(filename, FileMode.Create); - byte[] info = new UTF8Encoding(true).GetBytes(sb.ToString()); - fs.Write(info, 0, info.Length); } /// @@ -151,23 +152,24 @@ where T : DrawningLocomotive // /// true - загрузка прошла успешно, false - ошибка при загрузке данных public void LoadData(string filename) { - if (!File.Exists(filename)) { - throw new Exception("Файл не существует"); + throw new FileNotFoundException(filename); } + using (StreamReader fs = File.OpenText(filename)) { string str = fs.ReadLine(); - if (str == null || str.Length == 0) + if (string.IsNullOrEmpty(str)) { - throw new Exception("В файле нет данных"); - + throw new EmptyFileExeption(filename); } + if (!str.StartsWith(_collectionKey)) { - throw new Exception("В файле неверные данные"); + throw new FileFormatException(filename); } + _storages.Clear(); string strs = ""; while ((strs = fs.ReadLine()) != null) @@ -177,34 +179,33 @@ where T : DrawningLocomotive { continue; } - - ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType); - if (collection == null) - { - throw new Exception("Не удалось создать коллекцию"); - } + CollectionInfo? collectionInfo = + CollectionInfo.GetCollectionInfo(record[0]) ?? + throw new CollectionNoInfoException("Не удалось определить информацию коллекции:" + record[0]); + + ICollectionGenericObjects? collection = + StorageCollection.CreateCollection(collectionInfo.CollectionType) ?? + throw new CollectionNoTypeException("Не удалось определить тип коллекции:" + record[1]); collection.MaxCount = Convert.ToInt32(record[1]); + string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); foreach (string elem in set) { - if (elem?.CreateDrawningLocomotive() is T locomotive) + if (elem?.CreateDrawningLocomotive() is T macine) { try { - if (collection.Insert(locomotive) == -1) - { - throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]); - } + collection.Insert(macine); } - catch (CollectionOverflowException ex) + catch (Exception ex) { - throw new Exception("Коллекция переполнена", ex); - + throw new FileFormatException(filename, ex); } } } - _storages.Add(record[0], collection); + + _storages.Add(collectionInfo, collection); } } } diff --git a/ProjectElectricLocomotive/Exceptions/CollectionExistsException.cs b/ProjectElectricLocomotive/Exceptions/CollectionExistsException.cs new file mode 100644 index 0000000..e361e03 --- /dev/null +++ b/ProjectElectricLocomotive/Exceptions/CollectionExistsException.cs @@ -0,0 +1,21 @@ +using ProjectElectricLocomotive.CollectionGenericObjects; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectElectricLocomotive.Exceptions +{ + [Serializable] + public class CollectionExistsException : Exception + { + public CollectionExistsException() : base() { } + public CollectionExistsException(CollectionInfo collectionInfo) : base("Коллекция " + collectionInfo + " уже создана") { } + public CollectionExistsException(string name, Exception exception) : base("Коллекция " + name + " уже создана", exception) + { } + protected CollectionExistsException(SerializationInfo info, StreamingContext contex) : base(info, contex) { } + } +} + diff --git a/ProjectElectricLocomotive/Exceptions/CollectionNoInfoException.cs b/ProjectElectricLocomotive/Exceptions/CollectionNoInfoException.cs new file mode 100644 index 0000000..4880ce2 --- /dev/null +++ b/ProjectElectricLocomotive/Exceptions/CollectionNoInfoException.cs @@ -0,0 +1,20 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectElectricLocomotive.Exceptions +{ + public class CollectionNoInfoException : Exception + { + public CollectionNoInfoException() : base() { } + public CollectionNoInfoException(string message) : base(message) { } + public CollectionNoInfoException(string message, Exception exception) : + base(message, exception) + { } + protected CollectionNoInfoException(SerializationInfo info, StreamingContext + contex) : base(info, contex) { } + } +} \ No newline at end of file diff --git a/ProjectElectricLocomotive/Exceptions/CollectionNoTypeException.cs b/ProjectElectricLocomotive/Exceptions/CollectionNoTypeException.cs new file mode 100644 index 0000000..783122f --- /dev/null +++ b/ProjectElectricLocomotive/Exceptions/CollectionNoTypeException.cs @@ -0,0 +1,22 @@ +using ProjectElectricLocomotive.CollectionGenericObjects; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectElectricLocomotive.Exceptions +{ + [Serializable] + + public class CollectionNoTypeException : Exception + { + public CollectionNoTypeException() : base() { } + public CollectionNoTypeException(string message) : base(message) { } + public CollectionNoTypeException(string message, Exception exception) : + base(message, exception) + { } + protected CollectionNoTypeException(SerializationInfo info, StreamingContext contex) : base(info, contex) { } + } +} diff --git a/ProjectElectricLocomotive/Exceptions/EmptyFileExeption.cs b/ProjectElectricLocomotive/Exceptions/EmptyFileExeption.cs new file mode 100644 index 0000000..1e414b8 --- /dev/null +++ b/ProjectElectricLocomotive/Exceptions/EmptyFileExeption.cs @@ -0,0 +1,21 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectElectricLocomotive.Exceptions +{ + public class EmptyFileExeption : Exception + { + public EmptyFileExeption(string name) : base("Файл" + name + "пустой ") { } + public EmptyFileExeption() : base("В хранилище отсутствуют коллекции для сохранения") { } + public EmptyFileExeption(string name, string message) : base(message) { } + public EmptyFileExeption(string name, string message, Exception exception) : + base(message, exception) + { } + protected EmptyFileExeption(SerializationInfo info, StreamingContext + contex) : base(info, contex) { } + } +} diff --git a/ProjectElectricLocomotive/FormLocomotiveCollection.cs b/ProjectElectricLocomotive/FormLocomotiveCollection.cs index 6c1b65d..f4e54a7 100644 --- a/ProjectElectricLocomotive/FormLocomotiveCollection.cs +++ b/ProjectElectricLocomotive/FormLocomotiveCollection.cs @@ -195,14 +195,13 @@ public partial class FormLocomotiveCollection : Form /// private void RerfreshListBoxItems() { - listBoxCollection.Items.Clear(); for (int i = 0; i < _storageCollection.Keys?.Count; ++i) { - string? colName = _storageCollection.Keys?[i]; - if (!string.IsNullOrEmpty(colName)) + CollectionInfo? col = _storageCollection.Keys?[i]; + if (!col!.IsEmpty()) { - listBoxCollection.Items.Add(colName); + listBoxCollection.Items.Add(col); } } } @@ -219,18 +218,21 @@ public partial class FormLocomotiveCollection : Form MessageBox.Show("Коллекция не выбрана"); return; } + ICollectionGenericObjects? collection = - _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty]; + _storageCollection[ + CollectionInfo.GetCollectionInfo(listBoxCollection.SelectedItem.ToString()!) ?? + new CollectionInfo("", CollectionType.None, "")]; if (collection == null) { MessageBox.Show("Коллекция не проинициализирована"); return; } + switch (comboBoxSelectorCompany.Text) { - case "Депо": - _company = new LocomotiveDepo(pictureBox.Width, - pictureBox.Height, collection); + case "Хранилище": + _company = new LocomotiveDepo(pictureBox.Width, pictureBox.Height, collection); break; } panelCompanyTools.Enabled = true; @@ -246,25 +248,23 @@ public partial class FormLocomotiveCollection : Form /// private void buttonCollectionDel_Click(object sender, EventArgs e) { + // TODO прописать логику удаления элемента из коллекции + // нужно убедиться, что есть выбранная коллекция + // спросить у пользователя через MessageBox, что он подтверждает, что хочет удалить запись + // удалить и обновить ListBox if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null) { MessageBox.Show("Коллекция не выбрана"); return; } - try + if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) { - if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) - { - return; - } - _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString()); - RerfreshListBoxItems(); - _logger.LogInformation("Коллекция: " + listBoxCollection.SelectedItem.ToString() + " удалена"); - } - catch (Exception ex) - { - _logger.LogError("Ошибка: {Message}", ex.Message); + return; } + CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(listBoxCollection.SelectedItem.ToString()!); + _storageCollection.DelCollection(collectionInfo!); + _logger.LogInformation("Коллекция удалена"); + RerfreshListBoxItems(); } /// @@ -276,27 +276,29 @@ public partial class FormLocomotiveCollection : Form { if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked)) { - MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show("Не все данные заполнены", "Ошибка", + MessageBoxButtons.OK, MessageBoxIcon.Error); return; } + CollectionType collectionType = CollectionType.None; + if (radioButtonMassive.Checked) + { + collectionType = CollectionType.Massive; + } + else if (radioButtonList.Checked) + { + collectionType = CollectionType.List; + } try { - CollectionType collectionType = CollectionType.None; - if (radioButtonMassive.Checked) - { - collectionType = CollectionType.Massive; - } - else if (radioButtonList.Checked) - { - collectionType = CollectionType.List; - } - _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); + _storageCollection.AddCollection(new CollectionInfo(textBoxCollectionName.Text, collectionType, "ХЗ")); + _logger.LogInformation("Добавление коллекции"); RerfreshListBoxItems(); - _logger.LogInformation("Коллекция добавлена " + textBoxCollectionName.Text); } catch (Exception ex) { - _logger.LogError("Ошибка: {Message}", ex.Message); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogError($"Ошибка: {ex.Message}", ex.Message); } } -- 2.25.1 From b60f29db2b42867f74e76a3c09f40e8760d62af2 Mon Sep 17 00:00:00 2001 From: Tonb73 Date: Sun, 12 May 2024 13:28:05 +0300 Subject: [PATCH 5/6] Just killed a man, put a gun against his head, pull the trigger now he is dead... --- .../FormLocomotiveCollection.cs | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/ProjectElectricLocomotive/FormLocomotiveCollection.cs b/ProjectElectricLocomotive/FormLocomotiveCollection.cs index f4e54a7..b8d2928 100644 --- a/ProjectElectricLocomotive/FormLocomotiveCollection.cs +++ b/ProjectElectricLocomotive/FormLocomotiveCollection.cs @@ -96,12 +96,11 @@ public partial class FormLocomotiveCollection : Form _logger.LogInformation("Добавлен объект: " + locomotive.GetDataForSave()); } } - catch (ObjectNotFoundException) { } - catch (CollectionOverflowException ex) + catch (Exception ex) { - //MessageBox.Show("Не удалось добавить объект"); - MessageBox.Show(ex.Message); - _logger.LogError("Ошибка: {Message}", ex.Message); + MessageBox.Show($"Объект не добавлен: {ex.Message}", "Результат", MessageBoxButtons.OK, + MessageBoxIcon.Error); + _logger.LogError($"Ошибка: {ex.Message}", ex.Message); } } @@ -222,7 +221,7 @@ public partial class FormLocomotiveCollection : Form ICollectionGenericObjects? collection = _storageCollection[ CollectionInfo.GetCollectionInfo(listBoxCollection.SelectedItem.ToString()!) ?? - new CollectionInfo("", CollectionType.None, "")]; + new CollectionInfo("", CollectionType.None, "Description")]; if (collection == null) { MessageBox.Show("Коллекция не проинициализирована"); @@ -231,7 +230,7 @@ public partial class FormLocomotiveCollection : Form switch (comboBoxSelectorCompany.Text) { - case "Хранилище": + case "Депо": _company = new LocomotiveDepo(pictureBox.Width, pictureBox.Height, collection); break; } @@ -291,7 +290,7 @@ public partial class FormLocomotiveCollection : Form } try { - _storageCollection.AddCollection(new CollectionInfo(textBoxCollectionName.Text, collectionType, "ХЗ")); + _storageCollection.AddCollection(new CollectionInfo(textBoxCollectionName.Text, collectionType, "")); _logger.LogInformation("Добавление коллекции"); RerfreshListBoxItems(); } -- 2.25.1 From cfb42cde8d9d3bbc5e271261fde9d50135631237 Mon Sep 17 00:00:00 2001 From: Tonb73 Date: Mon, 13 May 2024 10:10:22 +0300 Subject: [PATCH 6/6] =?UTF-8?q?=D0=9B=D0=B0=D0=B1=D0=BE=D1=80=D0=B0=D1=82?= =?UTF-8?q?=D0=BE=D1=80=D0=BD=D0=B0=D1=8F=20=D1=80=D0=B0=D0=B1=D0=BE=D1=82?= =?UTF-8?q?=D0=B0=208?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Lab_1/Data_Structure.cpp | 1 - Lab_1/Data_Structure.h | 42 -------- Lab_1/Lab_1.sln | 31 ------ Lab_1/Lab_1.vcxproj | 139 ------------------------- Lab_1/Lab_1.vcxproj.filters | 30 ------ Lab_1/Source.cpp | 199 ------------------------------------ 6 files changed, 442 deletions(-) delete mode 100644 Lab_1/Data_Structure.cpp delete mode 100644 Lab_1/Data_Structure.h delete mode 100644 Lab_1/Lab_1.sln delete mode 100644 Lab_1/Lab_1.vcxproj delete mode 100644 Lab_1/Lab_1.vcxproj.filters delete mode 100644 Lab_1/Source.cpp diff --git a/Lab_1/Data_Structure.cpp b/Lab_1/Data_Structure.cpp deleted file mode 100644 index 16afe1c..0000000 --- a/Lab_1/Data_Structure.cpp +++ /dev/null @@ -1 +0,0 @@ -#include "Data_Structure.h" diff --git a/Lab_1/Data_Structure.h b/Lab_1/Data_Structure.h deleted file mode 100644 index 68c2813..0000000 --- a/Lab_1/Data_Structure.h +++ /dev/null @@ -1,42 +0,0 @@ -//#include -//#include -// -//#pragma once -// -//struct Node { -// int data; -// Node* next; -//}; -// -//class Data_Structure -//{ -//private: -// Node* head; -// struct Node { -// int data; -// Node* next; -// }; -//public: -// Data_Structure(){ -// head = NULL; -// } -// void addNode(int val){ -// Node* newNode = new Node; -// newNode->data = val; -// newNode->next = head; -// head = newNode; -// -// -// } -// void printList() { -// Node* currentNode = head; -// while (currentNode->next != NULL) { -// printf("%d", currentNode->data); -// currentNode = currentNode->next; -// -// } -// -// -// } -//}; -// diff --git a/Lab_1/Lab_1.sln b/Lab_1/Lab_1.sln deleted file mode 100644 index 76a53c9..0000000 --- a/Lab_1/Lab_1.sln +++ /dev/null @@ -1,31 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 17 -VisualStudioVersion = 17.7.34024.191 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Lab_1", "Lab_1.vcxproj", "{B3B62C1B-E8D8-4038-8DFD-248406A48EE2}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|x64 = Debug|x64 - Debug|x86 = Debug|x86 - Release|x64 = Release|x64 - Release|x86 = Release|x86 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {B3B62C1B-E8D8-4038-8DFD-248406A48EE2}.Debug|x64.ActiveCfg = Debug|x64 - {B3B62C1B-E8D8-4038-8DFD-248406A48EE2}.Debug|x64.Build.0 = Debug|x64 - {B3B62C1B-E8D8-4038-8DFD-248406A48EE2}.Debug|x86.ActiveCfg = Debug|Win32 - {B3B62C1B-E8D8-4038-8DFD-248406A48EE2}.Debug|x86.Build.0 = Debug|Win32 - {B3B62C1B-E8D8-4038-8DFD-248406A48EE2}.Release|x64.ActiveCfg = Release|x64 - {B3B62C1B-E8D8-4038-8DFD-248406A48EE2}.Release|x64.Build.0 = Release|x64 - {B3B62C1B-E8D8-4038-8DFD-248406A48EE2}.Release|x86.ActiveCfg = Release|Win32 - {B3B62C1B-E8D8-4038-8DFD-248406A48EE2}.Release|x86.Build.0 = Release|Win32 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {FF15C0FB-D559-46A6-B4E8-E461B8F5C363} - EndGlobalSection -EndGlobal diff --git a/Lab_1/Lab_1.vcxproj b/Lab_1/Lab_1.vcxproj deleted file mode 100644 index 0d6ac74..0000000 --- a/Lab_1/Lab_1.vcxproj +++ /dev/null @@ -1,139 +0,0 @@ - - - - - Debug - Win32 - - - Release - Win32 - - - Debug - x64 - - - Release - x64 - - - - 17.0 - Win32Proj - {b3b62c1b-e8d8-4038-8dfd-248406a48ee2} - Lab1 - 10.0 - - - - Application - true - v143 - Unicode - - - Application - false - v143 - true - Unicode - - - Application - true - v143 - Unicode - - - Application - false - v143 - true - Unicode - - - - - - - - - - - - - - - - - - - - - - Level3 - true - WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) - true - - - Console - true - - - - - Level3 - true - true - true - WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) - true - - - Console - true - true - true - - - - - Level3 - true - _DEBUG;_CONSOLE;%(PreprocessorDefinitions) - true - - - Console - true - - - - - Level3 - true - true - true - NDEBUG;_CONSOLE;%(PreprocessorDefinitions) - true - - - Console - true - true - true - - - - - - - - - - - - - \ No newline at end of file diff --git a/Lab_1/Lab_1.vcxproj.filters b/Lab_1/Lab_1.vcxproj.filters deleted file mode 100644 index 6d47a77..0000000 --- a/Lab_1/Lab_1.vcxproj.filters +++ /dev/null @@ -1,30 +0,0 @@ - - - - - {4FC737F1-C7A5-4376-A066-2A32D752A2FF} - cpp;c;cc;cxx;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx - - - {93995380-89BD-4b04-88EB-625FBE52EBFB} - h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd - - - {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms - - - - - Исходные файлы - - - Исходные файлы - - - - - Файлы заголовков - - - \ No newline at end of file diff --git a/Lab_1/Source.cpp b/Lab_1/Source.cpp deleted file mode 100644 index bbe0097..0000000 --- a/Lab_1/Source.cpp +++ /dev/null @@ -1,199 +0,0 @@ -/* - 4 - - - - - - , - , -*/ - -#include -#include -#include "Data_Structure.h" - -int unsorted_array[10] = { 2, 5, 1,8,3,4,7,6,9,0 }; -int arr[10] = { 2, 5, 1,8,3,4,7,6,9,0 }; -int n = 10; - -void Buble_sort() { - for (int i = 0; i < n; i++) { - for (int j = n - 1; j > i; j--) { - if (arr[j - 1] > arr[j]) { - int temp = arr[j]; - arr[j] = arr[j - 1]; - arr[j - 1] = temp; - } - } - } -} - - -void Merge(int arr[], int begin, int end) { - int mid = begin + (end - begin) / 2; - int i = begin; - int j = mid + 1; - int d[11] = { 0 }; - int k = 0; - - while (i <= mid && j <= end) { - if (arr[i] <= arr[j]) { - d[k] = arr[i]; - i++; - } - else { - d[k] = arr[j]; - j++; - } - k++; - } - while (i <= mid) { - d[k] = arr[i]; - k++; - i++; - } - while (j <= end) { - d[k] = arr[j]; - k++; - j++; - } - for (i = 0; i < k; i++) { - arr[begin + i] = d[i]; - } - -} - -void Merge_sort(int* arr, int left, int right) { - int temp = 0; - if (left < right) { - if (right - left == 1) { - if (arr[left] > arr[right]) { - temp = arr[left]; - arr[left] = arr[right]; - arr[right] = temp; - } - } - else { - Merge_sort(arr, left, (right - left) / 2); - Merge_sort(arr, left + (right - left) / 2 + 1, right); - Merge(arr, left, right); - } - } - -} - - -void Shake_sort() { - int direction = 0; - int left = arr[0]; - int left_index = 0; - int right = arr[n]; - int right_index = n; - for (int _ = 0; _ < n - 1; _++) { - if (direction == 0) { - for (int i = left_index; i < right_index - 1; i++) { - if (arr[i] > arr[i + 1]) { - int temp = arr[i]; - arr[i] = arr[i + 1]; - arr[i + 1] = temp; - } - } - if (right != arr[right_index]) { - for (int i = n; i > 0; i--) { - if (arr[i] == right) { - right_index = i; - } - } - } - direction = 1; - } - else { - for (int j = right_index; j > left_index; j--) { - if (arr[j] < arr[j - 1]) { - int temp1 = arr[j]; - arr[j] = arr[j - 1]; - arr[j - 1] = temp1; - } - } - if (left != arr[left_index]) { - for (int i = 0; i < n; i++) { - if (arr[i] == left) { - left_index = i; - } - } - } - } - direction = 0; - } - -} - -void print_list() { - for (int i = 0; i < n; i++) { - printf("%d ", arr[i]); - } - printf("\n"); -} - - - -struct Node { - int student_year; - int student_group; - struct Node* next; - - -}; - -struct Node* first = NULL; - - - -void s_addToHead(int year, int group) { - struct Node* NewNode = (struct Node*)malloc(sizeof(NewNode)); - NewNode->student_year = year; - NewNode->student_group = group; - NewNode->next = first; - - first = NewNode; - -} - -void s_deleteFromHead() { - struct Node* DelNode = first; - int val1 = DelNode->student_year; - int val2 = DelNode->student_group; - - first = first->next; - printf("****|PI-%d, %d| - Deleted\n", val2, val1); - -} - -void s_print() { - struct Node* i = first; - while (i) { - printf("|PI-%d, %d|\n", i->student_group, i->student_year); - i = i->next; - } - - -} - - -int main() { - s_addToHead(2020, 12); - s_addToHead(2021, 13); - s_addToHead(2022, 14); - s_addToHead(2024, 15); - s_print(); - printf("------------------------\n"); - s_deleteFromHead(); - s_print(); - - print_list(); - Shake_sort(); - //Merge_sort(arr, 0, n - 1); - print_list(); - //Data_structure newStructure; - - - return 0; -} \ No newline at end of file -- 2.25.1