Лабораторная работа 8

This commit is contained in:
Daria 2024-06-03 10:27:14 +04:00
parent ed9c654fb2
commit 63411533e8
12 changed files with 473 additions and 99 deletions

View File

@ -65,7 +65,7 @@ public abstract class AbstractCompany
{
return -1;
}
return company._collection.Insert(car);
return company._collection.Insert(car, new DrawningTrackedVehicleEqutables());
}
/// <summary>
/// Перегрузка оператора удаления для класса
@ -111,6 +111,11 @@ public abstract class AbstractCompany
}
return bitmap;
}
/// <summary>
/// Сортировка
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
public void Sort(IComparer<DrawningTrackedVehicle?> comparer) => _collection?.CollectionSort(comparer);
/// <summary>
/// Вывод заднего фона

View File

@ -0,0 +1,77 @@
namespace Excavator.CollectionGenericObjects;
/// <summary>
/// Класс, хранящиий информацию по коллекции
/// </summary>
public class CollectionInfo : IEquatable<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 Excavator.CollectionGenericObjects;
using Excavator.Drawnings;
namespace Excavator.CollectionGenericObjects;
/// <summary>
/// Интерфейс описания действий для набора хранимых объектов
@ -21,16 +23,18 @@ public interface ICollectionGenericObjects<T>
/// Добавление объекта в коллекцию
/// </summary>
/// <param name="obj">Добавляемый объект</param>
/// <param name="comparer">Cравнение двух объектов</param>
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
int Insert(T obj);
int Insert(T obj, IEqualityComparer<T?>? comparer = null);
/// <summary>
/// Добавление объекта в коллекцию на конкретную позицию
/// </summary>
/// <param name="obj">Добавляемый объект</param>
/// <param name="position">Позиция</param>
/// <param name="comparer">Cравнение двух объектов</param>
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
int Insert(T obj, int position);
int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null);
/// <summary>
/// Удаление объекта из коллекции с конкретной позиции
@ -56,4 +60,9 @@ public interface ICollectionGenericObjects<T>
/// </summary>
/// <returns>Поэлементый вывод элементов коллекции</returns>
IEnumerable<T?> GetItems();
/// <summary>
/// Сортировка коллекции
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
void CollectionSort(IComparer<T?> comparer);
}

View File

@ -1,4 +1,6 @@
using Excavator.Exceptions;
using Excavator.Drawnings;
using Excavator.Exceptions;
using System.Linq;
namespace Excavator.CollectionGenericObjects;
@ -43,8 +45,16 @@ 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 (comparer != null)
{
if (_collection.Contains(obj, comparer))
{
throw new ObjectAlreadyInCollectionException();
}
}
if (Count == _maxCount)
{
throw new CollectionOverflowException(Count);
@ -54,9 +64,17 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
return _collection.Count;
}
public int Insert(T obj, int position)
public int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
{
// TODO выброс ошибки, если выход за границы списка
// TODO выброс ошибки, если переполнение
if (comparer != null)
{
if (_collection.Contains(obj, comparer))
{
throw new ObjectAlreadyInCollectionException();
}
}
if (position < 0 || position > Count)
{
throw new PositionOutOfCollectionException(position);
@ -89,4 +107,8 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
yield return _collection[i];
}
}
public void CollectionSort(IComparer<T?> comparer)
{
_collection.Sort(comparer);
}
}

View File

@ -1,4 +1,5 @@

using Excavator.Drawnings;
using Excavator.Exceptions;
namespace Excavator.CollectionGenericObjects;
@ -62,8 +63,20 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
return _collection[position];
}
public int Insert(T excavator)
public int Insert(T excavator, IEqualityComparer<T?>? comparer = null)
{
if (comparer != null)
{
foreach (T? item in _collection)
{
if ((comparer as IEqualityComparer<DrawningTrackedVehicle>).Equals(excavator as DrawningTrackedVehicle, item as DrawningTrackedVehicle))
{
throw new ObjectAlreadyInCollectionException();
}
}
}
for (int i = 0; i < Count; i++)
{
if (_collection[i] == null)
@ -75,9 +88,20 @@ 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)
{
if (comparer != null)
{
foreach (T? item in _collection)
{
if ((comparer as IEqualityComparer<DrawningTrackedVehicle>).Equals(obj as DrawningTrackedVehicle, item as DrawningTrackedVehicle))
{
throw new ObjectAlreadyInCollectionException();
}
}
}
if (position < 0 || position >= Count)
{
throw new PositionOutOfCollectionException(position);
@ -97,6 +121,7 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
return i;
}
}
for (int i = position - 1; i >= 0; i--)
{
if (_collection[i] == null)
@ -133,4 +158,9 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
yield return _collection[i];
}
}
public void CollectionSort(IComparer<T?> comparer)
{
Array.Sort(_collection, comparer);
}
}

View File

@ -14,38 +14,41 @@ 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>
/// Добавление коллекции в хранилище
/// добваление коллекции в хранилище
/// </summary>
/// <param name="name">Название коллекции</param>
/// <param name="name">название коллекции</param>
/// <param name="collectionType">тип коллекции</param>
public void AddCollection(string name, CollectionType collectionType)
public void AddCollection(CollectionInfo info)
{
if (string.IsNullOrEmpty(name)) return;
if (_storages.ContainsKey(name)) return;
if (collectionType == CollectionType.None) return;
if (collectionType == CollectionType.Massive)
if (info == null || _storages.ContainsKey(info))
{
_storages[name] = new MassiveGenericObjects<T>();
return;
}
else if (collectionType == CollectionType.List)
if (info.CollectionType == CollectionType.Massive)
{
_storages[name] = new ListGenericObjects<T>();
_storages.Add(info, new MassiveGenericObjects<T>());
}
if (info.CollectionType == CollectionType.List)
{
_storages.Add(info, new ListGenericObjects<T>());
}
}
@ -53,14 +56,14 @@ public class StorageCollection<T>
/// Удаление коллекции
/// </summary>
/// <param name="name"></param>
public void DelCollection(string name)
public void DelCollection(CollectionInfo info)
{
if (name == null || !_storages.ContainsKey(name))
if (info == null || !_storages.ContainsKey(info))
{
return;
}
_storages.Remove(name);
_storages.Remove(info);
}
/// <summary>
@ -68,13 +71,16 @@ public class StorageCollection<T>
/// </summary>
/// <param name="name">Название коллекции</param>
/// <returns></returns>
public ICollectionGenericObjects<T>? this[string name]
public ICollectionGenericObjects<T>? this[CollectionInfo info]
{
get
{
if (name == null || !_storages.ContainsKey(name)) { return null; }
return _storages[name];
if (_storages.ContainsKey(info))
{
return _storages[info];
}
return null;
}
}
/// <summary>
@ -106,35 +112,34 @@ public class StorageCollection<T>
File.Delete(filename);
}
using (StreamWriter writer = new StreamWriter(filename))
using (StreamWriter sw = new StreamWriter(filename))
{
writer.Write(_collectionKey);
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages)
sw.Write(_collectionKey);
foreach (KeyValuePair<CollectionInfo, ICollectionGenericObjects<T>> value in _storages)
{
writer.Write(Environment.NewLine);
sw.Write(Environment.NewLine);
// не сохраняем пустые коллекции
if (value.Value.Count == 0)
{
continue;
}
writer.Write(value.Key);
writer.Write(_separatorForKeyValue);
writer.Write(value.Value.GetCollectionType);
writer.Write(_separatorForKeyValue);
writer.Write(value.Value.MaxCount);
writer.Write(_separatorForKeyValue);
sw.Write(value.Key);
sw.Write(_separatorForKeyValue);
sw.Write(value.Value.MaxCount);
sw.Write(_separatorForKeyValue);
foreach (T? item in value.Value.GetItems())
{
string data = item?.GetDataForSave() ?? string.Empty;
if (string.IsNullOrEmpty(data))
{
continue;
}
writer.Write(data);
writer.Write(_separatorItems);
sw.Write(data);
sw.Write(_separatorItems);
}
}
}
@ -151,45 +156,43 @@ public class StorageCollection<T>
throw new FileNotFoundException("Файл не существует");
}
using (StreamReader reader = File.OpenText(filename))
using (StreamReader sr = new(filename))
{
string? str = reader.ReadLine();
if (str == null || str.Length == 0)
string line = sr.ReadLine();
if (line == null || line.Length == 0)
{
throw new FileFormatException("В файле нет данных");
}
if (!str.Equals(_collectionKey))
if (!line.Equals(_collectionKey))
{
//если нет такой записи, то это не те данные
throw new FileFormatException("В файле неверные данные");
}
_storages.Clear();
string? strs = "";
while ((strs = reader.ReadLine()) != null)
while ((line = sr.ReadLine()) != null)
{
string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 4)
string[] record = line.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
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("Не удалось создать коллекцию");
}
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<T>? collection = StorageCollection<T>.CreateCollection(collectionInfo.CollectionType) ??
throw new Exception("Не удалось создать коллекцию");
collection.MaxCount = Convert.ToInt32(record[1]);
string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
if (elem?.CreateDrawningTrackedVehicle() is T ship)
if (elem?.CreateDrawningTrackedVehicle() is T machine)
{
try
{
if (collection.Insert(ship) == -1)
if (collection.Insert(machine, new DrawningTrackedVehicleEqutables()) == -1)
{
throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]);
}
@ -198,13 +201,18 @@ public class StorageCollection<T>
{
throw new OverflowException("Коллекция переполнена", ex);
}
catch (ObjectAlreadyInCollectionException ex)
{
throw new InvalidOperationException("Объект уже присутствует в коллекции", ex);
}
}
}
_storages.Add(record[0], collection);
_storages.Add(collectionInfo, collection);
}
}
}
/// <summary>
/// Создание коллекции по типу
/// </summary>

View File

@ -0,0 +1,66 @@
using Excavator.Entities;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
namespace Excavator.Drawnings;
/// <summary>
/// Реализация сравнения двух объектов класса-прорисовки
/// </summary>
public class DrawningTrackedVehicleEqutables : IEqualityComparer<DrawningTrackedVehicle?>
{
public bool Equals(DrawningTrackedVehicle? x, DrawningTrackedVehicle? y)
{
if (x == null || x.EntityTrackedVehicle == null)
{
return false;
}
if (y == null || y.EntityTrackedVehicle == null)
{
return false;
}
if (x.GetType().Name != y.GetType().Name)
{
return false;
}
if (x.EntityTrackedVehicle.Speed != y.EntityTrackedVehicle.Speed)
{
return false;
}
if (x.EntityTrackedVehicle.Weight != y.EntityTrackedVehicle.Weight)
{
return false;
}
if (x.EntityTrackedVehicle.BodyColor != y.EntityTrackedVehicle.BodyColor)
{
return false;
}
if (x is DrawningExcavator && y is DrawningExcavator)
{
if ((x.EntityTrackedVehicle as EntityExcavator)?.AdditionalColor !=
(y.EntityTrackedVehicle as EntityExcavator)?.AdditionalColor)
{
return false;
}
if ((x.EntityTrackedVehicle as EntityExcavator)?.Supports !=
(y.EntityTrackedVehicle as EntityExcavator)?.Supports)
{
return false;
}
if ((x.EntityTrackedVehicle as EntityExcavator)?.Bucket !=
(y.EntityTrackedVehicle as EntityExcavator)?.Bucket)
{
return false;
}
}
return true;
}
public int GetHashCode([DisallowNull] DrawningTrackedVehicle? obj)
{
return obj.GetHashCode();
}
}

View File

@ -0,0 +1,46 @@
using Excavator.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Excavator.Drawnings;
/// <summary>
/// Сравнение по цвету, скорости, весу
/// </summary>
public class DrawningTrackedVehicleCompareByColor : IComparer<DrawningTrackedVehicle?>
{
public int Compare(DrawningTrackedVehicle? x, DrawningTrackedVehicle? y)
{
if (x == null || x.EntityTrackedVehicle == null)
{
return 1;
}
if (y == null || y.EntityTrackedVehicle == null)
{
return -1;
}
var bodyColorCompare = y.EntityTrackedVehicle.BodyColor.Name.CompareTo(x.EntityTrackedVehicle.BodyColor.Name);
if (bodyColorCompare != 0)
{
return bodyColorCompare;
}
if (x is DrawningExcavator && y is DrawningExcavator)
{
var additionalColorCompare = (y.EntityTrackedVehicle as EntityExcavator).AdditionalColor.Name.CompareTo(
(x.EntityTrackedVehicle as EntityExcavator).AdditionalColor.Name);
if (additionalColorCompare != 0)
{
return additionalColorCompare;
}
}
var speedCompare = y.EntityTrackedVehicle.Speed.CompareTo(x.EntityTrackedVehicle.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return y.EntityTrackedVehicle.Weight.CompareTo(x.EntityTrackedVehicle.Weight);
}
}

View File

@ -0,0 +1,35 @@
using Excavator.Drawnings;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Excavator.CollectionGenericObjects;
/// <summary>
/// Сравнение по типу, скорости, весу
/// </summary>
public class DrawningTrackedVehicleCompareByType : IComparer<DrawningTrackedVehicle?>
{
public int Compare(DrawningTrackedVehicle? x, DrawningTrackedVehicle? y)
{
if (x == null || x.EntityTrackedVehicle == null)
{
return 1;
}
if (y == null || y.EntityTrackedVehicle == null)
{
return -1;
}
if (x.GetType().Name != y.GetType().Name)
{
return y.GetType().Name.CompareTo(x.GetType().Name);
}
var speedCompare = y.EntityTrackedVehicle.Speed.CompareTo(x.EntityTrackedVehicle.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return y.EntityTrackedVehicle.Weight.CompareTo(x.EntityTrackedVehicle.Weight);
}
}

View File

@ -0,0 +1,21 @@
using System.Runtime.Serialization;
namespace Excavator.Exceptions;
/// <summary>
/// Класс, описывающий ошибку переполнения коллекции
/// </summary>
[Serializable]
internal class ObjectAlreadyInCollectionException : ApplicationException
{
public ObjectAlreadyInCollectionException(int index) : base("Такой объект уже присутствует в коллекции. Позиция " + index) { }
public ObjectAlreadyInCollectionException() : base() { }
public ObjectAlreadyInCollectionException(string message) : base(message) { }
public ObjectAlreadyInCollectionException(string message, Exception exception) : base(message, exception) { }
protected ObjectAlreadyInCollectionException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}

View File

@ -52,6 +52,8 @@
LoadToolStripMenuItem = new ToolStripMenuItem();
saveFileDialog = new SaveFileDialog();
openFileDialog = new OpenFileDialog();
buttonSortByType = new Button();
buttonSortByColor = new Button();
groupBox1.SuspendLayout();
panelCompanyTools.SuspendLayout();
panelStorage.SuspendLayout();
@ -75,6 +77,8 @@
//
// panelCompanyTools
//
panelCompanyTools.Controls.Add(buttonSortByColor);
panelCompanyTools.Controls.Add(buttonSortByType);
panelCompanyTools.Controls.Add(buttonAddTrackedVehicle);
panelCompanyTools.Controls.Add(buttonRefresh);
panelCompanyTools.Controls.Add(buttonGoToCheck);
@ -82,9 +86,9 @@
panelCompanyTools.Controls.Add(buttonDelExcavator);
panelCompanyTools.Dock = DockStyle.Bottom;
panelCompanyTools.Enabled = false;
panelCompanyTools.Location = new Point(3, 514);
panelCompanyTools.Location = new Point(3, 409);
panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(215, 268);
panelCompanyTools.Size = new Size(215, 373);
panelCompanyTools.TabIndex = 9;
//
// buttonAddTrackedVehicle
@ -294,6 +298,26 @@
openFileDialog.FileName = "openFileDialog1";
openFileDialog.Filter = "txt file | *.txt";
//
// buttonSortByType
//
buttonSortByType.Location = new Point(18, 256);
buttonSortByType.Name = "buttonSortByType";
buttonSortByType.Size = new Size(171, 45);
buttonSortByType.TabIndex = 7;
buttonSortByType.Text = "Сортировка по типу";
buttonSortByType.UseVisualStyleBackColor = true;
buttonSortByType.Click += buttonSortByType_Click;
//
// buttonSortByColor
//
buttonSortByColor.Location = new Point(18, 307);
buttonSortByColor.Name = "buttonSortByColor";
buttonSortByColor.Size = new Size(171, 45);
buttonSortByColor.TabIndex = 8;
buttonSortByColor.Text = "Сортировка по цвету";
buttonSortByColor.UseVisualStyleBackColor = true;
buttonSortByColor.Click += buttonSortByColor_Click;
//
// FormTrackedVehicleCollection
//
AutoScaleDimensions = new SizeF(8F, 20F);
@ -343,5 +367,7 @@
private ToolStripMenuItem LoadToolStripMenuItem;
private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog;
private Button buttonSortByColor;
private Button buttonSortByType;
}
}

View File

@ -174,33 +174,34 @@ public partial class FormTrackedVehicleCollection : Form
pictureBox.Image = _company.Show();
}
/// <summary>
/// Добавление коллекции
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonCollectionAdd_Click(object sender, EventArgs e)
/// Добавление коллекции
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonCollectionAdd_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked))
{
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked))
{
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: Заполнены не все данные для добавления коллекции");
return;
}
CollectionType collectionType = CollectionType.None;
if (radioButtonMassive.Checked)
{
collectionType = CollectionType.Massive;
}
else if (radioButtonList.Checked)
{
collectionType = CollectionType.List;
}
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
_logger.LogInformation($"Добавлена коллекция: {textBoxCollectionName.Text} типа: {collectionType}");
RerfreshListBoxItems();
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: Заполнены не все данные для добавления коллекции");
return;
}
CollectionType collectionType = CollectionType.None;
if (radioButtonMassive.Checked)
{
collectionType = CollectionType.Massive;
}
else if (radioButtonList.Checked)
{
collectionType = CollectionType.List;
}
CollectionInfo collectionInfo = new CollectionInfo(textBoxCollectionName.Text, collectionType, string.Empty);
_storageCollection.AddCollection(collectionInfo);
_logger.LogInformation($"Добавлена коллекция: {textBoxCollectionName.Text} типа: {collectionType}");
RerfreshListBoxItems();
}
/// <summary>
/// Удаление коллекции
/// </summary>
@ -213,13 +214,15 @@ public partial class FormTrackedVehicleCollection : Form
MessageBox.Show("Коллекция не выбрана");
return;
}
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
if (MessageBox.Show("Вы уверены, что хотите удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
{
return;
}
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
_logger.LogInformation($"Удалена коллекция: {listBoxCollection.SelectedItem.ToString()}");
CollectionInfo collectionInfo = new CollectionInfo(listBoxCollection.SelectedItem.ToString(), CollectionType.None, string.Empty);
_storageCollection.DelCollection(collectionInfo);
_logger.LogInformation($"Удалена коллекция: {listBoxCollection.SelectedItem.ToString()}");
RerfreshListBoxItems();
}
/// <summary>
@ -230,7 +233,7 @@ public partial class FormTrackedVehicleCollection : 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);
@ -251,7 +254,8 @@ public partial class FormTrackedVehicleCollection : Form
return;
}
ICollectionGenericObjects<DrawningTrackedVehicle>? collection = _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty];
CollectionInfo collectionInfo = new CollectionInfo(listBoxCollection.SelectedItem.ToString(), CollectionType.None, string.Empty);
ICollectionGenericObjects<DrawningTrackedVehicle>? collection = _storageCollection[collectionInfo];
if (collection == null)
{
MessageBox.Show("Коллекция не проинициализирована");
@ -264,7 +268,6 @@ public partial class FormTrackedVehicleCollection : Form
_company = new Garage(pictureBox.Width, pictureBox.Height, collection);
break;
}
panelCompanyTools.Enabled = true;
RerfreshListBoxItems();
}
@ -314,7 +317,33 @@ public partial class FormTrackedVehicleCollection : Form
}
}
}
/// <summary>
/// Сортировка по типу
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonSortByType_Click(object sender, EventArgs e)
{
CompareTrackedVehicles(new DrawningTrackedVehicleCompareByType());
}
/// <summary>
/// Сортировка по цвету
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonSortByColor_Click(object sender, EventArgs e)
{
CompareTrackedVehicles(new DrawningTrackedVehicleCompareByColor());
}
private void CompareTrackedVehicles(IComparer<DrawningTrackedVehicle?> comparer)
{
if (_company == null)
{
return;
}
_company.Sort(comparer);
pictureBox.Image = _company.Show();
}
}