diff --git a/Monorail/Monorail/CollectionGenericObjects/AbstractCompany.cs b/Monorail/Monorail/CollectionGenericObjects/AbstractCompany.cs
index 8867108..2a747a7 100644
--- a/Monorail/Monorail/CollectionGenericObjects/AbstractCompany.cs
+++ b/Monorail/Monorail/CollectionGenericObjects/AbstractCompany.cs
@@ -40,8 +40,6 @@ public abstract class AbstractCompany
///
/// Вычисление максимального количества элементов, который можно разместить в окне
///
- //private int GetMaxCount => (_pictureWidth / _placeSizeWidth) * (_pictureHeight / _placeSizeHeight);
- //private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight);
private int GetMaxCount => (_pictureWidth / _placeSizeWidth) * (_pictureHeight / _placeSizeHeight);
///
@@ -66,7 +64,7 @@ public abstract class AbstractCompany
///
public static int operator +(AbstractCompany company, DrawningLocomotive locomotive)
{
- return company._collection.Insert(locomotive);
+ return company._collection.Insert(locomotive, new DrawningLocomotiveEqutables());
}
///
@@ -111,7 +109,7 @@ public abstract class AbstractCompany
}
return bitmap;
}
-
+
///
/// Вывод заднего фона
///
@@ -122,4 +120,10 @@ public abstract class AbstractCompany
/// Расстановка объектов
///
protected abstract void SetObjectsPosition();
+
+ ///
+ /// Сортировка
+ ///
+ /// Сравнитель объектов
+ public void Sort(IComparer comparer) => _collection?.CollectionSort(comparer);
}
diff --git a/Monorail/Monorail/CollectionGenericObjects/CollectionInfo.cs b/Monorail/Monorail/CollectionGenericObjects/CollectionInfo.cs
index 31c3c89..53607cc 100644
--- a/Monorail/Monorail/CollectionGenericObjects/CollectionInfo.cs
+++ b/Monorail/Monorail/CollectionGenericObjects/CollectionInfo.cs
@@ -6,6 +6,9 @@ using System.Threading.Tasks;
namespace Monorail.CollectionGenericObjects;
+///
+/// Класс, хранящий информацию по коллекции
+///
public class CollectionInfo : IEquatable
{
///
diff --git a/Monorail/Monorail/CollectionGenericObjects/ICollectionGenericObjects.cs b/Monorail/Monorail/CollectionGenericObjects/ICollectionGenericObjects.cs
index 7507321..358fafb 100644
--- a/Monorail/Monorail/CollectionGenericObjects/ICollectionGenericObjects.cs
+++ b/Monorail/Monorail/CollectionGenericObjects/ICollectionGenericObjects.cs
@@ -1,4 +1,5 @@
-using System;
+using Monorail.Drawnings;
+using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@@ -23,16 +24,18 @@ public interface ICollectionGenericObjects
/// Добавление объекта в коллекцию
///
/// Добавляемый объект
+ /// /// Сравнение двух объектов
/// true - вставка прошла удачно, false - вставка не удалась
- int Insert(T obj);
+ int Insert(T obj, IEqualityComparer? comparer = null);
///
/// Добавление объекта в коллекцию на конкретную позицию
///
/// Добавляемый объект
/// Позиция
+ /// /// Сравнение двух объектов
/// true - вставка прошла удачно, false - вставка не удалась
- int Insert(T obj, int position);
+ int Insert(T obj, int position, IEqualityComparer? comparer = null);
///
/// Удаление объекта из коллекции с конкретной позиции
@@ -58,4 +61,10 @@ public interface ICollectionGenericObjects
///
/// Поэлементый вывод элементов коллекции
IEnumerable GetItems();
+
+ ///
+ /// Сортировка коллекции
+ ///
+ ///
+ void CollectionSort(IComparer comparer);
}
diff --git a/Monorail/Monorail/CollectionGenericObjects/ListGenericObjects.cs b/Monorail/Monorail/CollectionGenericObjects/ListGenericObjects.cs
index f911cb2..e54bf8e 100644
--- a/Monorail/Monorail/CollectionGenericObjects/ListGenericObjects.cs
+++ b/Monorail/Monorail/CollectionGenericObjects/ListGenericObjects.cs
@@ -1,4 +1,5 @@
-using Monorail.Exceptions;
+using Monorail.Drawnings;
+using Monorail.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -64,9 +65,17 @@ public class ListGenericObjects : ICollectionGenericObjects
return _collection[position];
}
- public int Insert(T obj)
+ public int Insert(T obj, IEqualityComparer? comparer = null)
{
- // TODO выброс ошибки если переполнение
+ // Проверка, что такой объект уже есть
+ if (comparer != null)
+ {
+ if (_collection.Contains(obj, comparer))
+ {
+ throw new ObjectIsEqualException();
+ }
+ }
+ // Проверка, что не превышено максимальное количество элементов
if (Count == _maxCount)
{
throw new CollectionOverflowException(Count);
@@ -75,10 +84,17 @@ public class ListGenericObjects : ICollectionGenericObjects
return Count;
}
- public int Insert(T obj, int position)
+ public int Insert(T obj, int position, IEqualityComparer? comparer = null)
{
- // TODO выброс ошибки если переполнение
- // TODO выброс ошибки если за границу
+ //Проверка, что такой объект уже есть
+ if (comparer != null)
+ {
+ if (_collection.Contains(obj, comparer))
+ {
+ throw new ObjectNotFoundException();
+ }
+ }
+ // Проверка, что не превышено максимальное количество элементов
if (Count == _maxCount)
{
throw new CollectionOverflowException(Count);
@@ -111,4 +127,10 @@ public class ListGenericObjects : ICollectionGenericObjects
yield return _collection[i];
}
}
+
+
+ void ICollectionGenericObjects.CollectionSort(IComparer comparer)
+ {
+ _collection.Sort(comparer);
+ }
}
\ No newline at end of file
diff --git a/Monorail/Monorail/CollectionGenericObjects/MassiveGenericObjects.cs b/Monorail/Monorail/CollectionGenericObjects/MassiveGenericObjects.cs
index dbd0781..c94c84f 100644
--- a/Monorail/Monorail/CollectionGenericObjects/MassiveGenericObjects.cs
+++ b/Monorail/Monorail/CollectionGenericObjects/MassiveGenericObjects.cs
@@ -1,4 +1,5 @@
-using Monorail.Exceptions;
+using Monorail.Drawnings;
+using Monorail.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -44,9 +45,6 @@ public class MassiveGenericObjects : ICollectionGenericObjects
}
}
-
-
-
///
/// Конструктор
///
@@ -55,7 +53,7 @@ public class MassiveGenericObjects : ICollectionGenericObjects
_collection = Array.Empty();
}
- public T? Get(int position)
+ public T Get(int position)
{
// TODO выброс ошибки если выход за границу
// TODO выброс ошибки если объект пустой
@@ -70,42 +68,69 @@ public class MassiveGenericObjects : ICollectionGenericObjects
return _collection[position];
}
- public int Insert(T obj)
+ public int Insert(T obj, IEqualityComparer? comparer = null)
{
// Вставка в свободное место набора
- return Insert(obj, 0);
+ if (comparer != null)
+ {
+ foreach (T? item in _collection)
+ {
+ if ((comparer as IEqualityComparer).Equals(obj as DrawningLocomotive, item as DrawningLocomotive))
+ throw new ObjectIsEqualException();
+ }
+ }
+ int index = 0;
+ while (index < _collection.Length)
+ {
+ if (_collection[index] == null)
+ {
+ _collection[index] = obj;
+ return index;
+ }
+ ++index;
+ }
+ throw new CollectionOverflowException(Count);
}
- public int Insert(T obj, int position)
+ public int Insert(T obj, int position, IEqualityComparer? comparer = null)
{
+
+ // TODO выбрас ошибки, если есть такой объект в коллекции
+
// Проверка позиции
- if (position < 0 || position >= Count)
+ if (comparer != null)
{
- throw new PositionOutOfCollectionException(position);
+ foreach (T? item in _collection)
+ {
+ if ((comparer as IEqualityComparer).Equals(obj as DrawningLocomotive, item as DrawningLocomotive))
+ throw new ObjectIsEqualException();
+ }
}
- // Проверка, что элемент массива по этой позиции пустой
+ if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position);
if (_collection[position] == null)
{
_collection[position] = obj;
return position;
}
- //Свободное место после этой позиции
- for (int i = position + 1; i < Count; i++)
+ int index = position + 1;
+ while (index < _collection.Length)
{
- if (_collection[i] == null)
+ if (_collection[index] == null)
{
- _collection[i] = obj;
- return i;
+ _collection[index] = obj;
+ return index;
}
+ ++index;
}
- //Свободное место до этой позиции
- for (int i = position - 1; i >= 0; i--)
+ index = position - 1;
+ while (index >= 0)
{
- if (_collection[i] == null)
+ if (_collection[index] == null)
{
- _collection[i] = obj;
- return i;
+ _collection[index] = obj;
+ return index;
}
+ --index;
}
throw new CollectionOverflowException(Count);
}
@@ -137,5 +162,10 @@ public class MassiveGenericObjects : ICollectionGenericObjects
yield return _collection[i];
}
}
+
+ void ICollectionGenericObjects.CollectionSort(IComparer comparer)
+ {
+ Array.Sort(_collection, comparer);
+ }
}
diff --git a/Monorail/Monorail/CollectionGenericObjects/StorageCollection.cs b/Monorail/Monorail/CollectionGenericObjects/StorageCollection.cs
index eb75175..732401e 100644
--- a/Monorail/Monorail/CollectionGenericObjects/StorageCollection.cs
+++ b/Monorail/Monorail/CollectionGenericObjects/StorageCollection.cs
@@ -18,19 +18,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>();
}
///
@@ -42,18 +42,13 @@ public class StorageCollection
{
// TODO проверка, что name не пустой и нет в словаре записи с таким ключом
// TODO Прописать логику для добавления
- if (string.IsNullOrEmpty(name) || _storages.ContainsKey(name) || collectionType == CollectionType.None)
- {
- return;
- }
- if (collectionType == CollectionType.Massive)
- {
- _storages[name] = new MassiveGenericObjects();
- }
- if (collectionType == CollectionType.List)
- {
- _storages[name] = new ListGenericObjects();
- }
+ CollectionInfo collectionInfo = new CollectionInfo(name, collectionType, string.Empty);
+ if (_storages.ContainsKey(collectionInfo)) return;
+ if (collectionType == CollectionType.None) return;
+ else if (collectionType == CollectionType.Massive)
+ _storages[collectionInfo] = new MassiveGenericObjects();
+ else if (collectionType == CollectionType.List)
+ _storages[collectionInfo] = new ListGenericObjects();
}
///
@@ -63,10 +58,9 @@ public class StorageCollection
public void DelCollection(string name)
{
// TODO Прописать логику для удаления коллекции
- if (_storages.ContainsKey(name))
- {
- _storages.Remove(name);
- }
+ CollectionInfo collectionInfo = new CollectionInfo(name, CollectionType.None, string.Empty);
+ if (_storages.ContainsKey(collectionInfo))
+ _storages.Remove(collectionInfo);
}
///
@@ -78,14 +72,10 @@ public class StorageCollection
{
get
{
- if (_storages.ContainsKey(name))
- {
- return _storages[name];
- }
- else
- {
- return null;
- }
+ CollectionInfo collectionInfo = new CollectionInfo(name, CollectionType.None, string.Empty);
+ if (_storages.ContainsKey(collectionInfo))
+ return _storages[collectionInfo];
+ return null;
}
}
@@ -112,7 +102,7 @@ public class StorageCollection
{
if (_storages.Count == 0)
{
- throw new ArgumentException("В хранилище отсутствуют коллекции для сохранения");
+ throw new Exception("В хранилище отсутствуют коллекции для сохранения");
}
if (File.Exists(filename))
@@ -123,7 +113,7 @@ public class StorageCollection
using (StreamWriter writer = new StreamWriter(filename))
{
writer.Write(_collectionKey);
- foreach (KeyValuePair> value in _storages)
+ foreach (KeyValuePair> value in _storages)
{
writer.Write(Environment.NewLine);
// не сохраняем пустые коллекции
@@ -133,8 +123,6 @@ public class StorageCollection
}
writer.Write(value.Key);
writer.Write(_separatorForKeyValue);
- writer.Write(value.Value.GetCollectionType);
- writer.Write(_separatorForKeyValue);
writer.Write(value.Value.MaxCount);
writer.Write(_separatorForKeyValue);
foreach (T? item in value.Value.GetItems())
@@ -158,36 +146,40 @@ public class StorageCollection
{
if (!File.Exists(filename))
{
- throw new Exception("Файл не существует");
+ throw new FileNotFoundException("Файл не существует");
}
- using (StreamReader fs = File.OpenText(filename))
+
+ using (StreamReader read = File.OpenText(filename))
{
- string str = fs.ReadLine();
+ string str = read.ReadLine();
+
if (str == null || str.Length == 0)
{
throw new Exception("В файле нет данных");
}
+
if (!str.StartsWith(_collectionKey))
{
throw new Exception("В файле неверные данные");
}
+
_storages.Clear();
string strs = "";
- while ((strs = fs.ReadLine()) != null)
+ while ((strs = read.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("Не удалось определить тип коллекции:" + record[1]);
- }
- collection.MaxCount = Convert.ToInt32(record[2]);
- string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
+ 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[1]);
+
+ string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
if (elem?.CreateDrawningLocomotive() is T locomotive)
@@ -195,7 +187,9 @@ public class StorageCollection
try
{
if (collection.Insert(locomotive) == -1)
+ {
throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]);
+ }
}
catch (CollectionOverflowException ex)
{
@@ -203,7 +197,7 @@ public class StorageCollection
}
}
}
- _storages.Add(record[0], collection);
+ _storages.Add(collectionInfo, collection);
}
}
}
diff --git a/Monorail/Monorail/Drawnings/DrawningLocomotiveCompareByColor.cs b/Monorail/Monorail/Drawnings/DrawningLocomotiveCompareByColor.cs
new file mode 100644
index 0000000..6a537ec
--- /dev/null
+++ b/Monorail/Monorail/Drawnings/DrawningLocomotiveCompareByColor.cs
@@ -0,0 +1,38 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace Monorail.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/Monorail/Monorail/Drawnings/DrawningLocomotiveCompareByType.cs b/Monorail/Monorail/Drawnings/DrawningLocomotiveCompareByType.cs
new file mode 100644
index 0000000..a78f838
--- /dev/null
+++ b/Monorail/Monorail/Drawnings/DrawningLocomotiveCompareByType.cs
@@ -0,0 +1,40 @@
+using Monorail.Drawnings;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace Monorail.CollectionGenericObjects;
+
+///
+/// Сравнение по типу, скорости, весу
+///
+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/Monorail/Monorail/Drawnings/DrawningLocomotiveEqutables.cs b/Monorail/Monorail/Drawnings/DrawningLocomotiveEqutables.cs
new file mode 100644
index 0000000..786c95e
--- /dev/null
+++ b/Monorail/Monorail/Drawnings/DrawningLocomotiveEqutables.cs
@@ -0,0 +1,74 @@
+using Monorail.Entities;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace Monorail.Drawnings;
+
+public class DrawningLocomotiveEqutables : 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 DrawningMonorail && y is DrawningMonorail)
+ {
+ // TODO доделать логику сравнения дополнительных параметров
+ EntityMonorail EntityX = (EntityMonorail)x.EntityLocomotive;
+ EntityMonorail EntityY = (EntityMonorail)y.EntityLocomotive;
+
+ if (EntityX.AdditionalColor != EntityY.AdditionalColor)
+ {
+ return false;
+ }
+
+ if (EntityX.MagneticRail != EntityY.MagneticRail)
+ {
+ return false;
+ }
+
+ if (EntityX.SecondCabin != EntityY.SecondCabin)
+ {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ public int GetHashCode([DisallowNull] DrawningLocomotive obj)
+ {
+ return obj.GetHashCode();
+ }
+}
diff --git a/Monorail/Monorail/Drawnings/ExtentionDrawningLocomotive.cs b/Monorail/Monorail/Drawnings/ExtentionDrawningLocomotive.cs
index 448ad7b..aee3035 100644
--- a/Monorail/Monorail/Drawnings/ExtentionDrawningLocomotive.cs
+++ b/Monorail/Monorail/Drawnings/ExtentionDrawningLocomotive.cs
@@ -8,7 +8,7 @@ using System.Threading.Tasks;
namespace Monorail.Drawnings;
///
-/// Расширение для класса EntityCar
+/// Расширение для класса EntityLocomotive
///
public static class ExtentionDrawningLocomotive
{
diff --git a/Monorail/Monorail/Exceptions/AlreadyInCollectionException.cs b/Monorail/Monorail/Exceptions/AlreadyInCollectionException.cs
deleted file mode 100644
index 054036c..0000000
--- a/Monorail/Monorail/Exceptions/AlreadyInCollectionException.cs
+++ /dev/null
@@ -1,17 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Runtime.Serialization;
-using System.Text;
-using System.Threading.Tasks;
-
-namespace Monorail.Exceptions;
-
-[Serializable]
-internal class AlreadyInCollectionException : ApplicationException
-{
- public AlreadyInCollectionException() : base("Такой объект уже есть в коллекции") { }
- public AlreadyInCollectionException(string message) : base(message) { }
- public AlreadyInCollectionException(string message, Exception exception) : base(message, exception) { }
- protected AlreadyInCollectionException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
-}
\ No newline at end of file
diff --git a/Monorail/Monorail/Exceptions/ObjectIsEqualException.cs b/Monorail/Monorail/Exceptions/ObjectIsEqualException.cs
new file mode 100644
index 0000000..2991be8
--- /dev/null
+++ b/Monorail/Monorail/Exceptions/ObjectIsEqualException.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 Monorail.Exceptions;
+
+///
+/// Класс, описывающий ошибку переполнения коллекции
+///
+[Serializable]
+internal class ObjectIsEqualException : ApplicationException
+{
+ public ObjectIsEqualException() : base("Объект уже добавлен") { }
+ public ObjectIsEqualException(string message) : base(message) { }
+ public ObjectIsEqualException(string message, Exception exception) : base(message, exception) { }
+ protected ObjectIsEqualException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
+}
diff --git a/Monorail/Monorail/FormLocomotiveCollection.Designer.cs b/Monorail/Monorail/FormLocomotiveCollection.Designer.cs
index 6dc21da..5bdd7c3 100644
--- a/Monorail/Monorail/FormLocomotiveCollection.Designer.cs
+++ b/Monorail/Monorail/FormLocomotiveCollection.Designer.cs
@@ -52,6 +52,8 @@
loadToolStripMenuItem = new ToolStripMenuItem();
saveFileDialog = new SaveFileDialog();
openFileDialog = new OpenFileDialog();
+ buttonSortByType = new Button();
+ buttonSortByColor = new Button();
groupBoxTools.SuspendLayout();
panelCompanyTools.SuspendLayout();
panelStorage.SuspendLayout();
@@ -68,13 +70,15 @@
groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(752, 24);
groupBoxTools.Name = "groupBoxTools";
- groupBoxTools.Size = new Size(187, 548);
+ groupBoxTools.Size = new Size(187, 600);
groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты";
//
// panelCompanyTools
//
+ panelCompanyTools.Controls.Add(buttonSortByColor);
+ panelCompanyTools.Controls.Add(buttonSortByType);
panelCompanyTools.Controls.Add(buttonGoToCheck);
panelCompanyTools.Controls.Add(buttonAddLocomotive);
panelCompanyTools.Controls.Add(buttonRemoveLocomotiv);
@@ -82,15 +86,15 @@
panelCompanyTools.Controls.Add(buttonRefresh);
panelCompanyTools.Dock = DockStyle.Bottom;
panelCompanyTools.Enabled = false;
- panelCompanyTools.Location = new Point(3, 292);
+ panelCompanyTools.Location = new Point(3, 298);
panelCompanyTools.Name = "panelCompanyTools";
- panelCompanyTools.Size = new Size(181, 253);
+ panelCompanyTools.Size = new Size(181, 299);
panelCompanyTools.TabIndex = 9;
//
// buttonGoToCheck
//
buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
- buttonGoToCheck.Location = new Point(13, 176);
+ buttonGoToCheck.Location = new Point(13, 131);
buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(156, 39);
buttonGoToCheck.TabIndex = 5;
@@ -112,7 +116,7 @@
// buttonRemoveLocomotiv
//
buttonRemoveLocomotiv.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
- buttonRemoveLocomotiv.Location = new Point(13, 131);
+ buttonRemoveLocomotiv.Location = new Point(13, 86);
buttonRemoveLocomotiv.Name = "buttonRemoveLocomotiv";
buttonRemoveLocomotiv.Size = new Size(156, 39);
buttonRemoveLocomotiv.TabIndex = 4;
@@ -122,7 +126,7 @@
//
// maskedTextBox
//
- maskedTextBox.Location = new Point(13, 102);
+ maskedTextBox.Location = new Point(13, 57);
maskedTextBox.Mask = "00";
maskedTextBox.Name = "maskedTextBox";
maskedTextBox.Size = new Size(156, 23);
@@ -132,7 +136,7 @@
// buttonRefresh
//
buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
- buttonRefresh.Location = new Point(13, 221);
+ buttonRefresh.Location = new Point(13, 176);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(156, 39);
buttonRefresh.TabIndex = 6;
@@ -249,7 +253,7 @@
pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 24);
pictureBox.Name = "pictureBox";
- pictureBox.Size = new Size(752, 548);
+ pictureBox.Size = new Size(752, 600);
pictureBox.TabIndex = 1;
pictureBox.TabStop = false;
//
@@ -293,11 +297,31 @@
//
openFileDialog.Filter = "txt file | *.txt";
//
+ // buttonSortByType
+ //
+ buttonSortByType.Location = new Point(13, 221);
+ buttonSortByType.Name = "buttonSortByType";
+ buttonSortByType.Size = new Size(156, 32);
+ buttonSortByType.TabIndex = 7;
+ buttonSortByType.Text = "Сортировка по типу";
+ buttonSortByType.UseVisualStyleBackColor = true;
+ buttonSortByType.Click += buttonSortByType_Click;
+ //
+ // buttonSortByColor
+ //
+ buttonSortByColor.Location = new Point(13, 259);
+ buttonSortByColor.Name = "buttonSortByColor";
+ buttonSortByColor.Size = new Size(156, 31);
+ buttonSortByColor.TabIndex = 8;
+ buttonSortByColor.Text = "Сортировка по цвету";
+ buttonSortByColor.UseVisualStyleBackColor = true;
+ buttonSortByColor.Click += buttonSortByColor_Click;
+ //
// FormLocomotiveCollection
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
- ClientSize = new Size(939, 572);
+ ClientSize = new Size(939, 624);
Controls.Add(pictureBox);
Controls.Add(groupBoxTools);
Controls.Add(menuStrip);
@@ -342,5 +366,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/Monorail/Monorail/FormLocomotiveCollection.cs b/Monorail/Monorail/FormLocomotiveCollection.cs
index beb920d..4902931 100644
--- a/Monorail/Monorail/FormLocomotiveCollection.cs
+++ b/Monorail/Monorail/FormLocomotiveCollection.cs
@@ -29,7 +29,7 @@ public partial class FormLocomotiveCollection : Form
///
private AbstractCompany? _company = null;
-
+
///
/// Логер
///
@@ -37,7 +37,7 @@ public partial class FormLocomotiveCollection : Form
///
/// Конструктор
/// z
- public FormLocomotiveCollection(ILogger logger)
+ public FormLocomotiveCollection(ILogger logger)
{
InitializeComponent();
_storageCollection = new();
@@ -92,6 +92,11 @@ public partial class FormLocomotiveCollection : Form
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
+ catch (ObjectIsEqualException ex)
+ {
+ MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
+ _logger.LogError("Ошибка: {Message}", ex.Message);
+ }
}
///
@@ -136,17 +141,7 @@ public partial class FormLocomotiveCollection : Form
MessageBox.Show(ex.Message);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
- /*
- if (_company - pos != null)
- {
- MessageBox.Show("Объект удален");
- pictureBox.Image = _company.Show();
- }
- else
- {
- MessageBox.Show("Не удалось удалить объект");
- }
- */
+
}
@@ -215,28 +210,22 @@ public partial class FormLocomotiveCollection : Form
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked))
{
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
+ _logger.LogInformation("Не удалось добавить коллекцию: не все данные заполнены");
return;
}
- try
+ CollectionType collectionType = CollectionType.None;
+ if (radioButtonMassive.Checked)
{
- CollectionType collectionType = CollectionType.None;
- if (radioButtonMassive.Checked)
- {
- collectionType = CollectionType.Massive;
- }
- else if (radioButtonList.Checked)
- {
- collectionType = CollectionType.List;
- }
-
- _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
- RerfreshListBoxItems();
- _logger.LogInformation("Коллекция добавлена " + textBoxCollectionName.Text);
+ collectionType = CollectionType.Massive;
}
- catch (Exception ex)
+ else if (radioButtonList.Checked)
{
- _logger.LogError("Ошибка: {Message}", ex.Message);
+ collectionType = CollectionType.List;
}
+ _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
+ RerfreshListBoxItems();
+ _logger.LogInformation("Добавлена коллекция типа " + collectionType + " с названием "
+ + textBoxCollectionName.Text);
}
///
///
@@ -279,7 +268,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);
@@ -334,12 +323,12 @@ public partial class FormLocomotiveCollection : Form
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName);
}
- catch(Exception ex)
+ catch (Exception ex)
{
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
-
+
}
}
@@ -366,4 +355,39 @@ public partial class FormLocomotiveCollection : Form
}
}
}
+
+ ///
+ /// Сортировка по типу
+ ///
+ ///
+ ///
+ private void buttonSortByType_Click(object sender, EventArgs e)
+ {
+ CompareLocomotive(new DrawningLocomotiveCompareByType());
+ }
+
+ ///
+ /// Сортировка по цвету
+ ///
+ ///
+ ///
+ private void buttonSortByColor_Click(object sender, EventArgs e)
+ {
+ CompareLocomotive(new DrawningLocomotiveCompareByColor());
+ }
+
+ ///
+ /// Сортировка по сравнителю
+ ///
+ /// Сравнитель объектов
+ private void CompareLocomotive(IComparer comparer)
+ {
+ if (_company == null)
+ {
+ return;
+ }
+
+ _company.Sort(comparer);
+ pictureBox.Image = _company.Show();
+ }
}
\ No newline at end of file