diff --git a/WarmlyLocomotive/WarmlyLocomotive/CollectionGenericObjects/AbstractCompany.cs b/WarmlyLocomotive/WarmlyLocomotive/CollectionGenericObjects/AbstractCompany.cs
index ef1388f..190d256 100644
--- a/WarmlyLocomotive/WarmlyLocomotive/CollectionGenericObjects/AbstractCompany.cs
+++ b/WarmlyLocomotive/WarmlyLocomotive/CollectionGenericObjects/AbstractCompany.cs
@@ -59,9 +59,15 @@ public abstract class AbstractCompany
///
public static int operator +(AbstractCompany company, DrawningLocomotive locomotive)
{
- return company._collection.Insert(locomotive);
+ return company._collection.Insert(locomotive, new DrawiningLocomotiveEqutables());
}
+ ///
+ /// Сортировка
+ ///
+ /// Сравнитель объектов
+ public void Sort(IComparer comparer) => _collection?.CollectionSort(comparer);
+
///
/// Перегрузка оператора удаления для класса
///
diff --git a/WarmlyLocomotive/WarmlyLocomotive/CollectionGenericObjects/CollectionInfo.cs b/WarmlyLocomotive/WarmlyLocomotive/CollectionGenericObjects/CollectionInfo.cs
new file mode 100644
index 0000000..a527471
--- /dev/null
+++ b/WarmlyLocomotive/WarmlyLocomotive/CollectionGenericObjects/CollectionInfo.cs
@@ -0,0 +1,71 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace WarmlyLocomotive.CollectionGenericObjects;
+
+public class CollectionInfo
+{
+ ///
+ /// Название
+ ///
+ 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/WarmlyLocomotive/WarmlyLocomotive/CollectionGenericObjects/ICollectionGenericObjects.cs b/WarmlyLocomotive/WarmlyLocomotive/CollectionGenericObjects/ICollectionGenericObjects.cs
index 562358f..1dd9f7d 100644
--- a/WarmlyLocomotive/WarmlyLocomotive/CollectionGenericObjects/ICollectionGenericObjects.cs
+++ b/WarmlyLocomotive/WarmlyLocomotive/CollectionGenericObjects/ICollectionGenericObjects.cs
@@ -1,4 +1,6 @@
-namespace WarmlyLocomotive.CollectionGenericObjects;
+using WarmlyLocomotive.Drawnings;
+
+namespace WarmlyLocomotive.CollectionGenericObjects;
///
/// Интерфейс описания действий для набора хранимых объектов
@@ -22,7 +24,7 @@ public interface ICollectionGenericObjects
///
/// Добавляемый объект
/// true - вставка прошла удачно, false - вставка не удалась
- int Insert(T obj);
+ int Insert(T obj, IEqualityComparer? comparer = null);
///
/// Добавление объекта в коллекцию на конкретную позицию
@@ -30,7 +32,7 @@ public interface ICollectionGenericObjects
/// Добавляемый объект
/// Позиция
/// true - вставка прошла удачно, false - вставка не удалась
- int Insert(T obj, int position);
+ int Insert(T obj, int position, IEqualityComparer? comparer = null);
///
/// Удаление объекта из коллекции с конкретной позиции
@@ -56,4 +58,10 @@ public interface ICollectionGenericObjects
///
/// Поэлементый вывод элементов коллекции
IEnumerable GetItems();
+
+ ///
+ /// Сортировка коллекции
+ ///
+ /// Сравнитель объектов
+ void CollectionSort(IComparer comparer);
}
\ No newline at end of file
diff --git a/WarmlyLocomotive/WarmlyLocomotive/CollectionGenericObjects/ListGenericObjects.cs b/WarmlyLocomotive/WarmlyLocomotive/CollectionGenericObjects/ListGenericObjects.cs
index 8270f6f..2169bc3 100644
--- a/WarmlyLocomotive/WarmlyLocomotive/CollectionGenericObjects/ListGenericObjects.cs
+++ b/WarmlyLocomotive/WarmlyLocomotive/CollectionGenericObjects/ListGenericObjects.cs
@@ -57,18 +57,25 @@ public class ListGenericObjects : ICollectionGenericObjects
return _collection[position];
}
- public int Insert(T obj)
+ public int Insert(T obj, IEqualityComparer? comparer = null)
{
// TODO проверка, что не превышено максимальное количество элементов
if (Count == _maxCount)
{
throw new CollectionOverflowException(Count);
}
+ if (comparer != null)
+ {
+ if (_collection.Contains(obj, comparer))
+ {
+ throw new ObjectIsExistException(obj);
+ }
+ }
// TODO вставка в конец набора
_collection.Add(obj);
return _collection.Count;
}
- public int Insert(T obj, int position)
+ public int Insert(T obj, int position, IEqualityComparer? comparer = null)
{
// TODO проверка, что не превышено максимальное количество элементов
if (Count == _maxCount)
@@ -81,6 +88,13 @@ public class ListGenericObjects : ICollectionGenericObjects
throw new PositionOutOfCollectionException(position);
}
// TODO вставка по позиции
+ if (comparer != null)
+ {
+ if (_collection.Contains(obj, comparer))
+ {
+ throw new ObjectIsExistException(obj);
+ }
+ }
_collection.Insert(position, obj);
return position;
}
@@ -104,4 +118,9 @@ public class ListGenericObjects : ICollectionGenericObjects
yield return _collection[i];
}
}
+
+ public void CollectionSort(IComparer comparer)
+ {
+ _collection.Sort(comparer);
+ }
}
diff --git a/WarmlyLocomotive/WarmlyLocomotive/CollectionGenericObjects/MassiveGenericObjects.cs b/WarmlyLocomotive/WarmlyLocomotive/CollectionGenericObjects/MassiveGenericObjects.cs
index 30a909e..6c37f4b 100644
--- a/WarmlyLocomotive/WarmlyLocomotive/CollectionGenericObjects/MassiveGenericObjects.cs
+++ b/WarmlyLocomotive/WarmlyLocomotive/CollectionGenericObjects/MassiveGenericObjects.cs
@@ -62,8 +62,18 @@ public class MassiveGenericObjects : ICollectionGenericObjects
return _collection[position];
}
- public int Insert(T obj)
+ public int Insert(T obj, IEqualityComparer? comparer = null)
{
+ if (comparer != null)
+ {
+ foreach (T? item in _collection)
+ {
+ if (comparer.Equals(item, obj))
+ {
+ throw new ObjectIsExistException(item);
+ }
+ }
+ }
// TODO вставка в свободное место набора
for (int i = 0; i < _collection.Length; i++)
{
@@ -76,16 +86,23 @@ public class MassiveGenericObjects : ICollectionGenericObjects
throw new CollectionOverflowException(Count);
}
- public int Insert(T obj, int position)
+ public int Insert(T obj, int position, IEqualityComparer? comparer = null)
{
// TODO проверка позиции
if (position > _collection.Length || position < 0)
{
throw new PositionOutOfCollectionException(position);
}
- // TODO проверка, что элемент массива по этой позиции пустой, если нет, то
- // ищется свободное место после этой позиции и идет вставка туда
- // если нет после, ищем до
+ if (comparer != null)
+ {
+ foreach (T? item in _collection)
+ {
+ if (comparer.Equals(item, obj))
+ {
+ throw new ObjectIsExistException(item);
+ }
+ }
+ }
if (_collection[position] == null)
{
_collection[position] = obj;
@@ -138,4 +155,8 @@ public class MassiveGenericObjects : ICollectionGenericObjects
yield return _collection[i];
}
}
+ public void CollectionSort(IComparer comparer)
+ {
+ Array.Sort(_collection, comparer);
+ }
}
diff --git a/WarmlyLocomotive/WarmlyLocomotive/CollectionGenericObjects/StorageCollection.cs b/WarmlyLocomotive/WarmlyLocomotive/CollectionGenericObjects/StorageCollection.cs
index 7b0d2da..0d63f95 100644
--- a/WarmlyLocomotive/WarmlyLocomotive/CollectionGenericObjects/StorageCollection.cs
+++ b/WarmlyLocomotive/WarmlyLocomotive/CollectionGenericObjects/StorageCollection.cs
@@ -1,4 +1,5 @@
using System.Text;
+using System.Xml.Linq;
using WarmlyLocomotive.Drawnings;
using WarmlyLocomotive.Exceptions;
@@ -29,19 +30,19 @@ public class StorageCollection
///
/// Словарь (хранилище) с коллекциями
///
- 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>();
}
///
@@ -51,19 +52,23 @@ public class StorageCollection
/// тип коллекции
public void AddCollection(string name, CollectionType collectionType)
{
- // TODO проверка, что name не пустой и нет в словаре записи с таким ключом
- if (name == null || _storages.ContainsKey(name))
+ CollectionInfo collectionInfo = new CollectionInfo(name, collectionType, string.Empty);
+
+ if (_storages.ContainsKey(collectionInfo) || name == null)
{
return;
}
- // TODO Прописать логику для добавления
- if (collectionType == CollectionType.List)
+ if (collectionType == CollectionType.None)
{
- _storages.Add(name, new ListGenericObjects());
+ return;
}
- if (collectionType == CollectionType.Massive)
+ else if (collectionType == CollectionType.Massive)
{
- _storages.Add(name, new MassiveGenericObjects());
+ _storages[collectionInfo] = new MassiveGenericObjects();
+ }
+ else if (collectionType == CollectionType.List)
+ {
+ _storages[collectionInfo] = new ListGenericObjects();
}
}
@@ -73,12 +78,11 @@ public class StorageCollection
/// Название коллекции
public void DelCollection(string name)
{
- if (name == null || !_storages.ContainsKey(name))
+ CollectionInfo collectionInfo = new CollectionInfo(name, CollectionType.None, string.Empty);
+ if (_storages.ContainsKey(collectionInfo))
{
- return;
+ _storages.Remove(collectionInfo);
}
- // TODO Прописать логику для удаления коллекции
- _storages.Remove(name);
}
///
@@ -90,10 +94,10 @@ public class StorageCollection
{
get
{
- // TODO Продумать логику получения объекта
- if (_storages.ContainsKey(name))
+ CollectionInfo collectionInfo = new CollectionInfo(name, CollectionType.None, string.Empty);
+ if (_storages.ContainsKey(collectionInfo))
{
- return _storages[name];
+ return _storages[collectionInfo];
}
return null;
}
@@ -119,7 +123,7 @@ public class StorageCollection
using FileStream fs = new(filename, FileMode.Create);
using StreamWriter sw = new StreamWriter(fs);
sw.WriteLine(_collectionKey);
- foreach (KeyValuePair> value in _storages)
+ foreach (KeyValuePair> value in _storages)
{
sw.Write(Environment.NewLine);
// не сохраняем пустые коллекции
@@ -129,8 +133,6 @@ public class StorageCollection
}
sw.Write(value.Key);
sw.Write(_separatorForKeyValue);
- sw.Write(value.Value.GetCollectionType);
- sw.Write(_separatorForKeyValue);
sw.Write(value.Value.MaxCount);
sw.Write(_separatorForKeyValue);
@@ -176,21 +178,18 @@ public class StorageCollection
while ((line = reader.ReadLine()) != null)
{
string[] record = line.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 InvalidOperationException("Не удалось создать коллекцию");
- }
+ CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(record[0]) ?? throw new Exception("Не удалось определить информацию коллекции: " + record[0]);
+ ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionInfo.CollectionType) ?? throw new InvalidOperationException("Не удалось создать коллекцию");
- 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 locomotive)
@@ -209,10 +208,9 @@ public class StorageCollection
}
}
- _storages.Add(record[0], collection);
+ _storages.Add(collectionInfo, collection);
}
}
- //return true;
}
///
@@ -229,5 +227,4 @@ public class StorageCollection
_ => null,
};
}
-
}
diff --git a/WarmlyLocomotive/WarmlyLocomotive/Drawnings/DrawiningLocomotiveEqutables.cs b/WarmlyLocomotive/WarmlyLocomotive/Drawnings/DrawiningLocomotiveEqutables.cs
new file mode 100644
index 0000000..dae664d
--- /dev/null
+++ b/WarmlyLocomotive/WarmlyLocomotive/Drawnings/DrawiningLocomotiveEqutables.cs
@@ -0,0 +1,58 @@
+using System.Diagnostics.CodeAnalysis;
+using WarmlyLocomotive.Entities;
+
+namespace WarmlyLocomotive.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 DrawningWarmlyLocomotive && y is DrawningWarmlyLocomotive)
+ {
+ if (((EntityWarmlyLocomotive)x.EntityLocomotive).AdditionalColor != ((EntityWarmlyLocomotive)y.EntityLocomotive).AdditionalColor)
+ {
+ return false;
+ }
+ if (((EntityWarmlyLocomotive)x.EntityLocomotive).Chimney != ((EntityWarmlyLocomotive)y.EntityLocomotive).Chimney)
+ {
+ return false;
+ }
+ if (((EntityWarmlyLocomotive)x.EntityLocomotive).Compartment != ((EntityWarmlyLocomotive)y.EntityLocomotive).Compartment)
+ {
+ return false;
+ }
+ }
+ return true;
+ }
+ public int GetHashCode([DisallowNull] DrawningLocomotive obj)
+ {
+ return obj.GetHashCode();
+ }
+}
diff --git a/WarmlyLocomotive/WarmlyLocomotive/Drawnings/DrawningLocomotiveCompareByColor.cs b/WarmlyLocomotive/WarmlyLocomotive/Drawnings/DrawningLocomotiveCompareByColor.cs
new file mode 100644
index 0000000..1bc8f9d
--- /dev/null
+++ b/WarmlyLocomotive/WarmlyLocomotive/Drawnings/DrawningLocomotiveCompareByColor.cs
@@ -0,0 +1,33 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace WarmlyLocomotive.Drawnings;
+
+public class DrawningLocomotiveCompareByColor : IComparer
+{
+ public int Compare(DrawningLocomotive? x, DrawningLocomotive? y)
+ {
+ if (x == null || x.EntityLocomotive == null)
+ {
+ return 1;
+ }
+ if (y == null || y.EntityLocomotive == null)
+ {
+ return -1;
+ }
+ var bodycolorCompare = x.EntityLocomotive.BodyColor.Name.CompareTo(y.EntityLocomotive.BodyColor.Name);
+ if (bodycolorCompare != 0)
+ {
+ return bodycolorCompare;
+ }
+ var speedCompare = x.EntityLocomotive.Speed.CompareTo(y.EntityLocomotive.Speed);
+ if (speedCompare != 0)
+ {
+ return speedCompare;
+ }
+ return x.EntityLocomotive.Weight.CompareTo(y.EntityLocomotive.Weight);
+ }
+}
diff --git a/WarmlyLocomotive/WarmlyLocomotive/Drawnings/DrawningLocomotiveCompareByType.cs b/WarmlyLocomotive/WarmlyLocomotive/Drawnings/DrawningLocomotiveCompareByType.cs
new file mode 100644
index 0000000..09cbc7e
--- /dev/null
+++ b/WarmlyLocomotive/WarmlyLocomotive/Drawnings/DrawningLocomotiveCompareByType.cs
@@ -0,0 +1,35 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace WarmlyLocomotive.Drawnings;
+
+///
+/// Сравнение по типу, скорости, весу
+///
+public class DrawningLocomotiveCompareByType : 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);
+ }
+}
diff --git a/WarmlyLocomotive/WarmlyLocomotive/Exceptions/ObjectIsExistException.cs b/WarmlyLocomotive/WarmlyLocomotive/Exceptions/ObjectIsExistException.cs
new file mode 100644
index 0000000..cd0d75b
--- /dev/null
+++ b/WarmlyLocomotive/WarmlyLocomotive/Exceptions/ObjectIsExistException.cs
@@ -0,0 +1,12 @@
+using System.Runtime.Serialization;
+namespace WarmlyLocomotive.Exceptions;
+
+[Serializable]
+public class ObjectIsExistException : ApplicationException
+{
+ public ObjectIsExistException(object i) : base("В коллекции существует элемент ") { }
+ public ObjectIsExistException() : base() { }
+ public ObjectIsExistException(string message) : base(message) { }
+ public ObjectIsExistException(string message, Exception exception) : base(message, exception) { }
+ protected ObjectIsExistException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
+}
diff --git a/WarmlyLocomotive/WarmlyLocomotive/FormLocomotiveCollection.Designer.cs b/WarmlyLocomotive/WarmlyLocomotive/FormLocomotiveCollection.Designer.cs
index e8362b0..811983e 100644
--- a/WarmlyLocomotive/WarmlyLocomotive/FormLocomotiveCollection.Designer.cs
+++ b/WarmlyLocomotive/WarmlyLocomotive/FormLocomotiveCollection.Designer.cs
@@ -52,6 +52,8 @@
loadToolStripMenuItem = new ToolStripMenuItem();
saveFileDialog = new SaveFileDialog();
openFileDialog = new OpenFileDialog();
+ buttonSortByColor = new Button();
+ buttonSortByType = new Button();
groupBoxTools.SuspendLayout();
panelCompanyTools.SuspendLayout();
panelStorage.SuspendLayout();
@@ -68,13 +70,15 @@
groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(821, 28);
groupBoxTools.Name = "groupBoxTools";
- groupBoxTools.Size = new Size(193, 590);
+ groupBoxTools.Size = new Size(193, 656);
groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты";
//
// panelCompanyTools
//
+ panelCompanyTools.Controls.Add(buttonSortByColor);
+ panelCompanyTools.Controls.Add(buttonSortByType);
panelCompanyTools.Controls.Add(buttonAddLocomotive);
panelCompanyTools.Controls.Add(maskedTextBoxPosition);
panelCompanyTools.Controls.Add(buttonRefresh);
@@ -82,9 +86,9 @@
panelCompanyTools.Controls.Add(buttonGoToCheck);
panelCompanyTools.Dock = DockStyle.Bottom;
panelCompanyTools.Enabled = false;
- panelCompanyTools.Location = new Point(3, 341);
+ panelCompanyTools.Location = new Point(3, 344);
panelCompanyTools.Name = "panelCompanyTools";
- panelCompanyTools.Size = new Size(187, 246);
+ panelCompanyTools.Size = new Size(187, 309);
panelCompanyTools.TabIndex = 9;
//
// buttonAddLocomotive
@@ -100,7 +104,7 @@
//
// maskedTextBoxPosition
//
- maskedTextBoxPosition.Location = new Point(0, 57);
+ maskedTextBoxPosition.Location = new Point(6, 57);
maskedTextBoxPosition.Mask = "00";
maskedTextBoxPosition.Name = "maskedTextBoxPosition";
maskedTextBoxPosition.Size = new Size(175, 27);
@@ -110,7 +114,7 @@
// buttonRefresh
//
buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
- buttonRefresh.Location = new Point(0, 200);
+ buttonRefresh.Location = new Point(6, 183);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(172, 34);
buttonRefresh.TabIndex = 6;
@@ -121,7 +125,7 @@
// buttonRemoveLocomotive
//
buttonRemoveLocomotive.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
- buttonRemoveLocomotive.Location = new Point(-3, 90);
+ buttonRemoveLocomotive.Location = new Point(6, 90);
buttonRemoveLocomotive.Name = "buttonRemoveLocomotive";
buttonRemoveLocomotive.Size = new Size(172, 48);
buttonRemoveLocomotive.TabIndex = 4;
@@ -132,7 +136,7 @@
// buttonGoToCheck
//
buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
- buttonGoToCheck.Location = new Point(0, 144);
+ buttonGoToCheck.Location = new Point(6, 144);
buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(172, 33);
buttonGoToCheck.TabIndex = 5;
@@ -249,7 +253,7 @@
pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 28);
pictureBox.Name = "pictureBox";
- pictureBox.Size = new Size(821, 590);
+ pictureBox.Size = new Size(821, 656);
pictureBox.TabIndex = 1;
pictureBox.TabStop = false;
//
@@ -294,11 +298,33 @@
//
openFileDialog.Filter = "txt file | *.txt";
//
+ // buttonSortByColor
+ //
+ buttonSortByColor.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
+ buttonSortByColor.Location = new Point(6, 262);
+ buttonSortByColor.Name = "buttonSortByColor";
+ buttonSortByColor.Size = new Size(172, 34);
+ buttonSortByColor.TabIndex = 8;
+ buttonSortByColor.Text = "Сортировка по цвету";
+ buttonSortByColor.UseVisualStyleBackColor = true;
+ buttonSortByColor.Click += ButtonSortByColor_Click;
+ //
+ // buttonSortByType
+ //
+ buttonSortByType.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
+ buttonSortByType.Location = new Point(6, 223);
+ buttonSortByType.Name = "buttonSortByType";
+ buttonSortByType.Size = new Size(172, 33);
+ buttonSortByType.TabIndex = 7;
+ buttonSortByType.Text = "Сортировка по типу";
+ buttonSortByType.UseVisualStyleBackColor = true;
+ buttonSortByType.Click += ButtonSortByType_Click;
+ //
// FormLocomotiveCollection
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
- ClientSize = new Size(1014, 618);
+ ClientSize = new Size(1014, 684);
Controls.Add(pictureBox);
Controls.Add(groupBoxTools);
Controls.Add(menuStrip);
@@ -343,5 +369,7 @@
private ToolStripMenuItem loadToolStripMenuItem;
private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog;
+ private Button buttonSortByColor;
+ private Button buttonSortByType;
}
}
\ No newline at end of file
diff --git a/WarmlyLocomotive/WarmlyLocomotive/FormLocomotiveCollection.cs b/WarmlyLocomotive/WarmlyLocomotive/FormLocomotiveCollection.cs
index cfe4d50..670b568 100644
--- a/WarmlyLocomotive/WarmlyLocomotive/FormLocomotiveCollection.cs
+++ b/WarmlyLocomotive/WarmlyLocomotive/FormLocomotiveCollection.cs
@@ -69,18 +69,19 @@ public partial class FormLocomotiveCollection : Form
///
private void SetLocomotive(DrawningLocomotive? locomotive)
{
- if (_company == null || locomotive == null)
- {
- return;
- }
try
{
+ if (_company == null || locomotive == null)
+ {
+ return;
+ }
if (_company + locomotive >= 0)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
_logger.LogInformation("Объект добавлен: " + locomotive.GetDataForSave());
}
+
}
catch (CollectionOverflowException ex)
{
@@ -92,6 +93,11 @@ public partial class FormLocomotiveCollection : Form
MessageBox.Show(ex.Message);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
+ catch(ObjectIsExistException ex)
+ {
+ MessageBox.Show(ex.Message);
+ _logger.LogError("Ошибка: {Message}", ex.Message);
+ }
}
///
@@ -217,7 +223,6 @@ public partial class FormLocomotiveCollection : Form
}
catch (Exception ex)
{
- //MessageBox.Show(ex.Message);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
@@ -233,26 +238,20 @@ public partial class FormLocomotiveCollection : Form
// нужно убедиться, что есть выбранная коллекция
// спросить у пользователя через MessageBox, что он подтверждает, что хочет удалить запись
// удалить и обновить ListBox
- if (!radioButtonList.Checked && !radioButtonMassive.Checked || string.IsNullOrEmpty(textBoxCollectionName.Text))
+ if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
{
return;
}
- try
+ if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
{
- if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
- {
- return;
- }
- _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
- RerfreshListBoxItems();
- _logger.LogInformation("Коллекция удалена: " + listBoxCollection.SelectedItem.ToString());
- }
- catch (Exception ex)
- {
- _logger.LogError("Ошибка: {Message}", ex.Message);
+ return;
}
+ _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
+ RerfreshListBoxItems();
+ _logger.LogInformation("Коллекция удалена: " + listBoxCollection.SelectedItem.ToString());
}
+
///
/// Создание компании
///
@@ -271,14 +270,22 @@ public partial class FormLocomotiveCollection : Form
MessageBox.Show("Коллекция не проинициализирована");
return;
}
- switch (comboBoxSelectorCompany.Text)
+ try
{
- case "Депо":
- _company = new LocomotiveSharingService(pictureBox.Width, pictureBox.Height, collection);
- break;
+ switch (comboBoxSelectorCompany.Text)
+ {
+ case "Депо":
+ _company = new LocomotiveSharingService(pictureBox.Width, pictureBox.Height, collection);
+ break;
+ }
+ }
+ catch (ObjectNotFoundException)
+ {
+
}
panelCompanyTools.Enabled = true;
RerfreshListBoxItems();
+
}
///
@@ -289,7 +296,7 @@ public partial class FormLocomotiveCollection : Form
listBoxCollection.Items.Clear();
for (int i = 0; i < _storageCollection.Keys?.Count; ++i)
{
- string? colName = _storageCollection.Keys?[i];
+ string? colName = _storageCollection.Keys?[i].Name;
if (!string.IsNullOrEmpty(colName))
{
listBoxCollection.Items.Add(colName);
@@ -344,4 +351,38 @@ public partial class FormLocomotiveCollection : Form
}
}
}
+
+ ///
+ /// Сортировка по типу
+ ///
+ ///
+ ///
+ private void ButtonSortByType_Click(object sender, EventArgs e)
+ {
+ CompareLocomotives(new DrawningLocomotiveCompareByType());
+ }
+
+ ///
+ /// Сортировка по цвету
+ ///
+ ///
+ ///
+ private void ButtonSortByColor_Click(object sender, EventArgs e)
+ {
+ CompareLocomotives(new DrawningLocomotiveCompareByColor());
+ }
+
+ ///
+ /// Сортировка по сравнителю
+ ///
+ /// Сравнитель объектов
+ private void CompareLocomotives(IComparer comparer)
+ {
+ if (_company == null)
+ {
+ return;
+ }
+ _company.Sort(comparer);
+ pictureBox.Image = _company.Show();
+ }
}