После видео

This commit is contained in:
Tonb73 2024-05-11 12:20:57 +03:00
parent 733bc788b6
commit 289bcf43c7
7 changed files with 194 additions and 51 deletions

View File

@ -106,6 +106,12 @@ public abstract class AbstractCompany
return bitmap;
}
/// <summary>
/// Сортировка
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
public void Sort(IComparer<DrawningLocomotive?> comparer) => _collection?.CollectionSort(comparer);
/// <summary>
/// Вывод заднего фона
/// </summary>

View File

@ -0,0 +1,78 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectElectricLocomotive.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

@ -19,17 +19,17 @@ where T : DrawningLocomotive
/// <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>
/// Добавление коллекции в хранилище
@ -101,51 +101,49 @@ where T : DrawningLocomotive
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
/// <summary>
/// Сохранение информации по автомобилям в хранилище в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
public void SaveData(string filename)
{
if (_storages.Count == 0)
{
if (_storages.Count == 0)
throw new Exception("В хранилище отсутствуют коллекции для сохранения");
}
if (File.Exists(filename))
{
File.Delete(filename);
}
StringBuilder sb = new();
sb.Append(_collectionKey);
foreach (KeyValuePair<CollectionInfo, ICollectionGenericObjects<T>>
value in _storages)
{
sb.Append(Environment.NewLine);
// не сохраняем пустые коллекции
if (value.Value.Count == 0)
{
throw new Exception("В хранилище отсутствуют коллекции для сохранения");
continue;
}
if (File.Exists(filename))
sb.Append(value.Key);
sb.Append(_separatorForKeyValue);
sb.Append(value.Value.MaxCount);
sb.Append(_separatorForKeyValue);
foreach (T? item in value.Value.GetItems())
{
File.Delete(filename);
}
using (StreamWriter writer = new StreamWriter(filename))
{
writer.Write(_collectionKey);
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages)
string data = item?.GetDataForSave() ?? string.Empty;
if (string.IsNullOrEmpty(data))
{
StringBuilder sb = new(); // построитель строк
sb.Append(Environment.NewLine);
// не сохраняем пустые коллекции
if (value.Value.Count == 0)
{
continue;
}
sb.Append(value.Key);
sb.Append(_separatorForKeyValue);
sb.Append(value.Value.GetCollectionType);
sb.Append(_separatorForKeyValue);
sb.Append(value.Value.MaxCount);
sb.Append(_separatorForKeyValue);
foreach (T? item in value.Value.GetItems())
{
string data = item?.GetDataForSave() ?? string.Empty;
if (string.IsNullOrEmpty(data))
{
continue;
}
sb.Append(data);
sb.Append(_separatorItems);
}
writer.Write(sb);
continue;
}
sb.Append(data);
sb.Append(_separatorItems);
}
}
using FileStream fs = new(filename, FileMode.Create);
byte[] info = new UTF8Encoding(true).GetBytes(sb.ToString());
fs.Write(info, 0, info.Length);
}
/// <summary>
@ -177,26 +175,26 @@ where T : DrawningLocomotive
while ((strs = fs.ReadLine()) != null)
{
string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 4)
if (record.Length != 3)
{
continue;
}
CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]);
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
if (collection == null)
{
throw new Exception("Не удалось создать коллекцию");
}
collection.MaxCount = Convert.ToInt32(record[2]);
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
collection.MaxCount = Convert.ToInt32(record[1]);
string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
if (elem?.CreateDrawningLocomotive() is T truck)
if (elem?.CreateDrawningLocomotive() is T locomotive)
{
try
{
if (collection.Insert(truck) == -1)
if (collection.Insert(locomotive) == -1)
{
throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]);
}

View File

@ -9,7 +9,7 @@ namespace ProjectElectricLocomotive.Drawnings
/// <summary>
/// Сравнение по цвету, скорости, весу
/// </summary>
public class DrawningCarCompareByColor : IComparer<DrawningLocomotive?>
public class DrawningLocomotiveCompareByColor : IComparer<DrawningLocomotive?>
{
public int Compare(DrawningLocomotive? x, DrawningLocomotive? y)
{

View File

@ -9,7 +9,7 @@ namespace ProjectElectricLocomotive.Drawnings;
/// <summary>
/// Сравнение по типу, скорости, весу
/// </summary>
public class DrawningCarCompareByType : IComparer<DrawningLocomotive?>
public class DrawningLocomotiveCompareByType : IComparer<DrawningLocomotive?>
{
public int Compare(DrawningLocomotive? x, DrawningLocomotive? y)
{

View File

@ -52,6 +52,8 @@
LoadToolStripMenuItem = new ToolStripMenuItem();
openFileDialog = new OpenFileDialog();
saveFileDialog = new SaveFileDialog();
buttonSortByColor = new Button();
buttonSortByType = new Button();
groupBoxTools.SuspendLayout();
panelCompanyTools.SuspendLayout();
panelStorage.SuspendLayout();
@ -76,7 +78,9 @@
//
// panelCompanyTools
//
panelCompanyTools.Controls.Add(buttonSortByColor);
panelCompanyTools.Controls.Add(buttonAddLocomotive);
panelCompanyTools.Controls.Add(buttonSortByType);
panelCompanyTools.Controls.Add(maskedTextBox);
panelCompanyTools.Controls.Add(buttonDelLocomotive);
panelCompanyTools.Controls.Add(buttonRefresh);
@ -99,7 +103,7 @@
//
// maskedTextBox
//
maskedTextBox.Location = new Point(12, 146);
maskedTextBox.Location = new Point(12, 82);
maskedTextBox.Mask = "00";
maskedTextBox.Name = "maskedTextBox";
maskedTextBox.Size = new Size(193, 31);
@ -108,7 +112,7 @@
//
// buttonDelLocomotive
//
buttonDelLocomotive.Location = new Point(12, 183);
buttonDelLocomotive.Location = new Point(12, 119);
buttonDelLocomotive.Name = "buttonDelLocomotive";
buttonDelLocomotive.Size = new Size(193, 63);
buttonDelLocomotive.TabIndex = 5;
@ -118,7 +122,7 @@
//
// buttonRefresh
//
buttonRefresh.Location = new Point(12, 297);
buttonRefresh.Location = new Point(12, 233);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(193, 39);
buttonRefresh.TabIndex = 7;
@ -128,7 +132,7 @@
//
// buttonGoToCheck
//
buttonGoToCheck.Location = new Point(12, 252);
buttonGoToCheck.Location = new Point(12, 188);
buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(193, 39);
buttonGoToCheck.TabIndex = 6;
@ -288,6 +292,26 @@
//
saveFileDialog.Filter = "txt file | *.txt";
//
// buttonSortByColor
//
buttonSortByColor.Location = new Point(12, 323);
buttonSortByColor.Name = "buttonSortByColor";
buttonSortByColor.Size = new Size(193, 37);
buttonSortByColor.TabIndex = 9;
buttonSortByColor.Text = "Сортировка по цвет";
buttonSortByColor.UseVisualStyleBackColor = true;
buttonSortByColor.Click += buttonSortByColor_Click;
//
// buttonSortByType
//
buttonSortByType.Location = new Point(12, 278);
buttonSortByType.Name = "buttonSortByType";
buttonSortByType.Size = new Size(193, 39);
buttonSortByType.TabIndex = 8;
buttonSortByType.Text = "Сортировка по типу";
buttonSortByType.UseVisualStyleBackColor = true;
buttonSortByType.Click += buttonSortByType_Click;
//
// FormLocomotiveCollection
//
AutoScaleDimensions = new SizeF(10F, 25F);
@ -338,5 +362,7 @@
private ToolStripMenuItem LoadToolStripMenuItem;
private OpenFileDialog openFileDialog;
private SaveFileDialog saveFileDialog;
private Button buttonSortByColor;
private Button buttonSortByType;
}
}

View File

@ -31,7 +31,7 @@ public partial class FormLocomotiveCollection : Form
/// <summary>
/// Логер
/// </summary>
private readonly ILogger _logger;
private readonly ILogger _logger;
/// <summary>
/// Компания
@ -352,4 +352,39 @@ public partial class FormLocomotiveCollection : Form
}
}
}
/// <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="sender"></param>
/// <param name="e"></param>
private void buttonSortByType_Click(object sender, EventArgs e)
{
CompareLocomotives(new DrawningLocomotiveCompareByType());
}
/// <summary>
/// Сортировка по сравнителю
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
private void CompareLocomotives(IComparer<DrawningLocomotive?> comparer)
{
if (_company == null)
{
return;
}
_company.Sort(comparer);
pictureBox.Image = _company.Show();
}
}