PI-13 Kobin V.O. LabWork08 Simple #8

Closed
vkobi wants to merge 1 commits from LabWork08 into LabWork07
12 changed files with 404 additions and 75 deletions

View File

@ -59,9 +59,15 @@ public abstract class AbstractCompany
/// <returns></returns>
public static int operator +(AbstractCompany company, DrawningLocomotive locomotive)
{
return company._collection.Insert(locomotive);
return company._collection.Insert(locomotive, new DrawiningLocomotiveEqutables());
}
/// <summary>
/// Сортировка
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
public void Sort(IComparer<DrawningLocomotive?> comparer) => _collection?.CollectionSort(comparer);
/// <summary>
/// Перегрузка оператора удаления для класса
/// </summary>

View File

@ -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
{
/// <summary>
/// Название
/// </summary>
public string Name { get; private set; }
/// <summary>
/// Тип
/// </summary>
public CollectionType CollectionType { get; private set; }
/// <summary>
/// Описание
/// </summary>
public string Description { get; private set; }
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly string _separator = "-";
/// <summary>
/// Конструктор
/// </summary>
/// <param name="name">Название</param>
/// <param name="collectionType">Тип</param>
/// <param name="description">Описание</param>
public CollectionInfo(string name, CollectionType collectionType, string description)
{
Name = name;
CollectionType = collectionType;
Description = description;
}
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="data">Строка</param>
/// <returns>Объект или null</returns>
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();
}
}

View File

@ -1,4 +1,6 @@
namespace WarmlyLocomotive.CollectionGenericObjects;
using WarmlyLocomotive.Drawnings;
namespace WarmlyLocomotive.CollectionGenericObjects;
/// <summary>
/// Интерфейс описания действий для набора хранимых объектов
@ -22,7 +24,7 @@ public interface ICollectionGenericObjects<T>
/// </summary>
/// <param name="obj">Добавляемый объект</param>
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
int Insert(T obj);
int Insert(T obj, IEqualityComparer<T?>? comparer = null);
/// <summary>
/// Добавление объекта в коллекцию на конкретную позицию
@ -30,7 +32,7 @@ public interface ICollectionGenericObjects<T>
/// <param name="obj">Добавляемый объект</param>
/// <param name="position">Позиция</param>
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
int Insert(T obj, int position);
int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null);
/// <summary>
/// Удаление объекта из коллекции с конкретной позиции
@ -56,4 +58,10 @@ public interface ICollectionGenericObjects<T>
/// </summary>
/// <returns>Поэлементый вывод элементов коллекции</returns>
IEnumerable<T?> GetItems();
/// <summary>
/// Сортировка коллекции
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
void CollectionSort(IComparer<T?> comparer);
}

View File

@ -57,18 +57,25 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
return _collection[position];
}
public int Insert(T obj)
public int Insert(T obj, IEqualityComparer<T?>? 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<T?>? comparer = null)
{
// TODO проверка, что не превышено максимальное количество элементов
if (Count == _maxCount)
@ -81,6 +88,13 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
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<T> : ICollectionGenericObjects<T>
yield return _collection[i];
}
}
public void CollectionSort(IComparer<T?> comparer)
{
_collection.Sort(comparer);
}
}

View File

@ -62,8 +62,18 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
return _collection[position];
}
public int Insert(T obj)
public int Insert(T obj, IEqualityComparer<T?>? 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<T> : ICollectionGenericObjects<T>
throw new CollectionOverflowException(Count);
}
public int Insert(T obj, int position)
public int Insert(T obj, int position, IEqualityComparer<T?>? 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<T> : ICollectionGenericObjects<T>
yield return _collection[i];
}
}
public void CollectionSort(IComparer<T?> comparer)
{
Array.Sort(_collection, comparer);
}
}

View File

@ -1,4 +1,5 @@
using System.Text;
using System.Xml.Linq;
using WarmlyLocomotive.Drawnings;
using WarmlyLocomotive.Exceptions;
@ -29,19 +30,19 @@ public class StorageCollection<T>
/// <summary>
/// Словарь (хранилище) с коллекциями
/// </summary>
readonly Dictionary<string, ICollectionGenericObjects<T>> _storages;
readonly Dictionary<CollectionInfo, ICollectionGenericObjects<T>> _storages;
/// <summary>
/// Возвращение списка названий коллекций
/// </summary>
public List<string> Keys => _storages.Keys.ToList();
public List<CollectionInfo> Keys => _storages.Keys.ToList();
/// <summary>
/// Конструктор
/// </summary>
public StorageCollection()
{
_storages = new Dictionary<string, ICollectionGenericObjects<T>>();
_storages = new Dictionary<CollectionInfo, ICollectionGenericObjects<T>>();
}
/// <summary>
@ -51,19 +52,23 @@ public class StorageCollection<T>
/// <param name="collectionType">тип коллекции</param>
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<T>());
return;
}
if (collectionType == CollectionType.Massive)
else if (collectionType == CollectionType.Massive)
{
_storages.Add(name, new MassiveGenericObjects<T>());
_storages[collectionInfo] = new MassiveGenericObjects<T>();
}
else if (collectionType == CollectionType.List)
{
_storages[collectionInfo] = new ListGenericObjects<T>();
}
}
@ -73,12 +78,11 @@ public class StorageCollection<T>
/// <param name="name">Название коллекции</param>
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);
}
/// <summary>
@ -90,10 +94,10 @@ public class StorageCollection<T>
{
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<T>
using FileStream fs = new(filename, FileMode.Create);
using StreamWriter sw = new StreamWriter(fs);
sw.WriteLine(_collectionKey);
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages)
foreach (KeyValuePair<CollectionInfo, ICollectionGenericObjects<T>> value in _storages)
{
sw.Write(Environment.NewLine);
// не сохраняем пустые коллекции
@ -129,8 +133,6 @@ public class StorageCollection<T>
}
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<T>
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<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
if (collection == null)
{
throw new InvalidOperationException("Не удалось создать коллекцию");
}
CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(record[0]) ?? throw new Exception("Не удалось определить информацию коллекции: " + record[0]);
ICollectionGenericObjects<T>? collection = StorageCollection<T>.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<T>
}
}
_storages.Add(record[0], collection);
_storages.Add(collectionInfo, collection);
}
}
//return true;
}
/// <summary>
@ -229,5 +227,4 @@ public class StorageCollection<T>
_ => null,
};
}
}

View File

@ -0,0 +1,58 @@
using System.Diagnostics.CodeAnalysis;
using WarmlyLocomotive.Entities;
namespace WarmlyLocomotive.Drawnings;
/// <summary>
/// Реализация сравнения двух объектов класса-прорисовки
/// </summary>
public class DrawiningLocomotiveEqutables : IEqualityComparer<DrawningLocomotive?>
{
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)
Review

Зачем неоднократные преобразования, что мешает сделать это один раз?

Зачем неоднократные преобразования, что мешает сделать это один раз?
{
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();
}
}

View File

@ -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<DrawningLocomotive?>
{
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);
}
}

View File

@ -0,0 +1,35 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WarmlyLocomotive.Drawnings;
/// <summary>
/// Сравнение по типу, скорости, весу
/// </summary>
public class DrawningLocomotiveCompareByType : IComparer<DrawningLocomotive?>
{
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);
}
}

View File

@ -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) { }
}

View File

@ -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;
}
}

View File

@ -69,18 +69,19 @@ public partial class FormLocomotiveCollection : Form
/// <param name="car"></param>
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);
}
}
/// <summary>
@ -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());
}
/// <summary>
/// Создание компании
/// </summary>
@ -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();
}
/// <summary>
@ -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
}
}
}
/// <summary>
/// Сортировка по типу
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonSortByType_Click(object sender, EventArgs e)
{
CompareLocomotives(new DrawningLocomotiveCompareByType());
}
/// <summary>
/// Сортировка по цвету
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonSortByColor_Click(object sender, EventArgs e)
{
CompareLocomotives(new DrawningLocomotiveCompareByColor());
}
/// <summary>
/// Сортировка по сравнителю
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
private void CompareLocomotives(IComparer<DrawningLocomotive?> comparer)
{
if (_company == null)
{
return;
}
_company.Sort(comparer);
pictureBox.Image = _company.Show();
}
}