Lab8 in process

This commit is contained in:
DanilaSm08 2024-05-19 12:53:44 +04:00
parent 46b2d2d8ec
commit 23e695e60d
15 changed files with 409 additions and 93 deletions

View File

@ -1,5 +1,5 @@
using ProjectCleaningCar.Drawnings; using ProjectCleaningCar.Drawnings;
using ProjectSportCar.Exceptions; using ProjectCleaningCar.Exceptions;
namespace ProjectCleaningCar.CollectionGenericObjects; namespace ProjectCleaningCar.CollectionGenericObjects;
/// <summary> /// <summary>
@ -48,11 +48,15 @@ public abstract class AbstractCompany
/// Перегрузка оператора сложения для класса /// Перегрузка оператора сложения для класса
/// </summary> /// </summary>
/// <param name="company">Компания</param> /// <param name="company">Компания</param>
/// <param name="truck">Добавляемый объект</param> /// <param name="car">Добавляемый объект</param>
/// <returns></returns> /// <returns></returns>
public static int operator +(AbstractCompany company, DrawningTruck truck) public static int operator +(AbstractCompany company, DrawningTruck truck)
{ {
return company._collection?.Insert(truck) ?? -1; if (company._collection == null)
{
return -1;
}
return company._collection.Insert(truck, new DrawiningTruckEqutables());
} }
/// <summary> /// <summary>
@ -95,6 +99,11 @@ public abstract class AbstractCompany
} }
return bitmap; return bitmap;
} }
/// <summary>
/// Сортировка
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
public void Sort(IComparer<DrawningTruck?> comparer) => _collection?.CollectionSort(comparer);
/// <summary> /// <summary>
/// Вывод заднего фона /// Вывод заднего фона
/// </summary> /// </summary>

View File

@ -1,5 +1,5 @@
using ProjectCleaningCar.Drawnings; using ProjectCleaningCar.Drawnings;
using ProjectSportCar.Exceptions; using ProjectCleaningCar.Exceptions;
namespace ProjectCleaningCar.CollectionGenericObjects; namespace ProjectCleaningCar.CollectionGenericObjects;
/// <summary> /// <summary>

View File

@ -0,0 +1,71 @@
namespace ProjectCleaningCar.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

@ -28,16 +28,17 @@ where T : class
/// Добавление объекта в коллекцию /// Добавление объекта в коллекцию
/// </summary> /// </summary>
/// <param name="obj">Добавляемый объект</param> /// <param name="obj">Добавляемый объект</param>
/// <param name="comparer">Cравнение двух объектов</param>
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns> /// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
int Insert(T obj); int Insert(T obj, IEqualityComparer<T?>? comparer = null);
/// <summary> /// <summary>
/// Добавление объекта в коллекцию на конкретную позицию /// Добавление объекта в коллекцию на конкретную позицию
/// </summary> /// </summary>
/// <param name="obj">Добавляемый объект</param> /// <param name="obj">Добавляемый объект</param>
/// <param name="position">Позиция</param> /// <param name="position">Позиция</param>
/// <param name="comparer">Cравнение двух объектов</param>
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns> /// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
int Insert(T obj, int position); int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null);
/// <summary> /// <summary>
/// Удаление объекта из коллекции с конкретной позиции /// Удаление объекта из коллекции с конкретной позиции
@ -62,4 +63,9 @@ where T : class
/// </summary> /// </summary>
/// <returns>Поэлементый вывод элементов коллекции</returns> /// <returns>Поэлементый вывод элементов коллекции</returns>
IEnumerable<T?> GetItems(); IEnumerable<T?> GetItems();
/// <summary>
/// Сортировка коллекции
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
void CollectionSort(IComparer<T?> comparer);
} }

View File

@ -1,10 +1,4 @@
using ProjectCleaningCar.Exceptions; using ProjectCleaningCar.Exceptions;
using ProjectSportCar.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectCleaningCar.CollectionGenericObjects; namespace ProjectCleaningCar.CollectionGenericObjects;
/// <summary> /// <summary>
@ -53,24 +47,34 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
} }
public int Insert(T obj) public int Insert(T obj, IEqualityComparer<T?>? comparer)
{ {
if (_collection.Contains(obj, comparer))
{
throw new ObjectNotUniqueException();
}
if (Count == _maxCount) { throw new CollectionOverflowException(_collection.Count); } if (Count == _maxCount) { throw new CollectionOverflowException(_collection.Count); }
_collection.Add(obj); _collection.Add(obj);
return Count; return Count;
} }
public int Insert(T obj, int position) public int Insert(T obj, int position, IEqualityComparer<T?>? comparer)
{ {
if (_collection.Contains(obj, comparer))
{
throw new ObjectNotUniqueException(position);
}
if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(); if (position < 0 || position >= Count) throw new PositionOutOfCollectionException();
if (Count == _maxCount) throw new CollectionOverflowException(); if (Count == _maxCount) throw new CollectionOverflowException();
_collection.Insert(position, obj); _collection.Insert(position, obj);
return position; return position;
} }
public T Remove(int position) public T Remove(int position)
{ {
if (position < 0 || position >= _collection.Count) throw new PositionOutOfCollectionException(position); if (position < 0 || position >= _collection.Count) throw new PositionOutOfCollectionException(position);
@ -87,4 +91,9 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
yield return _collection[i]; yield return _collection[i];
} }
} }
public void CollectionSort(IComparer<T?> comparer)
{
_collection.Sort(comparer);
}
} }

View File

@ -1,5 +1,5 @@
using ProjectCleaningCar.Exceptions; using ProjectCleaningCar.Drawnings;
using ProjectSportCar.Exceptions; using ProjectCleaningCar.Exceptions;
namespace ProjectCleaningCar.CollectionGenericObjects; namespace ProjectCleaningCar.CollectionGenericObjects;
/// <summary> /// <summary>
@ -62,12 +62,12 @@ internal class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
return _collection[position]; return _collection[position];
} }
public int Insert(T obj) public int Insert(T obj, IEqualityComparer<T?>? comparer = null)
{ {
return Insert(obj, 0); return Insert(obj, 0, comparer);
} }
public int Insert(T obj, int position) public int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
{ {
if (!(position >= 0 && position < Count)) throw new PositionOutOfCollectionException(position); if (!(position >= 0 && position < Count)) throw new PositionOutOfCollectionException(position);
@ -77,6 +77,15 @@ internal class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
return position; return position;
} }
if (comparer != null)
{
foreach (T? item in _collection)
{
if ((comparer as IEqualityComparer<DrawningTruck>).Equals(obj as DrawningTruck, item as DrawningTruck))
throw new ObjectNotUniqueException(position);
}
}
for (int i = position + 1; i < Count; i++) for (int i = position + 1; i < Count; i++)
{ {
if (_collection[i] == null) if (_collection[i] == null)
@ -115,5 +124,10 @@ internal class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
yield return _collection[i]; yield return _collection[i];
} }
} }
public void CollectionSort(IComparer<T?> comparer)
{
Array.Sort(_collection, comparer);
}
} }

View File

@ -13,11 +13,11 @@ public class StorageCollection<T>
/// <summary> /// <summary>
/// Словарь (хранилище) с коллекциями /// Словарь (хранилище) с коллекциями
/// </summary> /// </summary>
readonly Dictionary<string, ICollectionGenericObjects<T>> _storages; readonly Dictionary<CollectionInfo, ICollectionGenericObjects<T>> _storages;
/// <summary> /// <summary>
/// Возвращение списка названий коллекций /// Возвращение списка названий коллекций
/// </summary> /// </summary>
public List<string> Keys => _storages.Keys.ToList(); public List<CollectionInfo> Keys => _storages.Keys.ToList();
/// <summary> /// <summary>
/// Ключевое слово, с которого должен начинаться файл /// Ключевое слово, с которого должен начинаться файл
@ -37,7 +37,7 @@ public class StorageCollection<T>
/// </summary> /// </summary>
public StorageCollection() public StorageCollection()
{ {
_storages = new Dictionary<string, ICollectionGenericObjects<T>>(); _storages = new Dictionary<CollectionInfo, ICollectionGenericObjects<T>>();
} }
/// <summary> /// <summary>
/// Добавление коллекции в хранилище /// Добавление коллекции в хранилище
@ -46,30 +46,20 @@ public class StorageCollection<T>
/// <param name="collectionType">тип коллекции</param> /// <param name="collectionType">тип коллекции</param>
public void AddCollection(string name, CollectionType collectionType) public void AddCollection(string name, CollectionType collectionType)
{ {
if (string.IsNullOrEmpty(name)) CollectionInfo collectionInfo = new CollectionInfo(name, collectionType, string.Empty);
{ if (name == null || _storages.ContainsKey(collectionInfo)) { return; }
throw new ArgumentException("Название коллекции не может быть пустым или null", nameof(name));
}
if (_storages.ContainsKey(name))
{
throw new ArgumentException($"Коллекция с именем {name} уже существует", nameof(name));
}
ICollectionGenericObjects<T> collection;
switch (collectionType) switch (collectionType)
{
case CollectionType.List:
collection = new ListGenericObjects<T>();
break;
case CollectionType.Massive:
collection = new MassiveGenericObjects<T>();
break;
default:
throw new ArgumentException($"Неизвестный тип коллекции: {collectionType}", nameof(collectionType));
}
_storages.Add(name, collection); {
case CollectionType.None:
return;
case CollectionType.Massive:
_storages.Add(collectionInfo, new MassiveGenericObjects<T> { });
return;
case CollectionType.List:
_storages.Add(collectionInfo, new ListGenericObjects<T> { });
return;
}
} }
/// <summary> /// <summary>
@ -78,10 +68,9 @@ public class StorageCollection<T>
/// <param name="name">Название коллекции</param> /// <param name="name">Название коллекции</param>
public void DelCollection(string name) public void DelCollection(string name)
{ {
if (_storages.ContainsKey(name)) CollectionInfo collectionInfo = new CollectionInfo(name, CollectionType.None, string.Empty);
{ if (name == null || !_storages.ContainsKey(collectionInfo)) { return; }
_storages.Remove(name); _storages.Remove(collectionInfo);
}
} }
/// <summary> /// <summary>
/// Доступ к коллекции /// Доступ к коллекции
@ -92,11 +81,9 @@ public class StorageCollection<T>
{ {
get get
{ {
if (_storages.TryGetValue(name, out ICollectionGenericObjects<T>? collection)) CollectionInfo collectionInfo = new CollectionInfo(name, CollectionType.None, string.Empty);
{ if (collectionInfo == null || !_storages.ContainsKey(collectionInfo)) { return null; }
return collection; return _storages[collectionInfo];
}
return null;
} }
} }
/// <summary> /// <summary>
@ -107,7 +94,7 @@ public class StorageCollection<T>
{ {
if (_storages.Count == 0) if (_storages.Count == 0)
{ {
throw new Exception("В хранилище отсутствуют коллекции для сохранения"); throw new ArgumentException("В хранилище отсутствуют коллекции для сохранения");
} }
if (File.Exists(filename)) if (File.Exists(filename))
@ -120,17 +107,16 @@ public class StorageCollection<T>
using (StreamWriter sw = new StreamWriter(filename)) using (StreamWriter sw = new StreamWriter(filename))
{ {
sw.WriteLine(_collectionKey.ToString()); sw.WriteLine(_collectionKey.ToString());
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> kvpair in _storages) foreach (KeyValuePair<CollectionInfo, ICollectionGenericObjects<T>> kvpair in _storages)
{ {
// не сохраняем пустые коллекции // не сохраняем пустые коллекции
if (kvpair.Value.Count == 0) if (kvpair.Value.Count == 0)
continue; continue;
sb.Append(kvpair.Key); sb.Append(kvpair.Key);
sb.Append(_separatorForKeyValue); sb.Append(_separatorForKeyValue);
sb.Append(kvpair.Value.GetCollectionType);
sb.Append(_separatorForKeyValue);
sb.Append(kvpair.Value.MaxCount); sb.Append(kvpair.Value.MaxCount);
sb.Append(_separatorForKeyValue); sb.Append(_separatorForKeyValue);
foreach (T? item in kvpair.Value.GetItems()) foreach (T? item in kvpair.Value.GetItems())
{ {
string data = item?.GetDataForSave() ?? string.Empty; string data = item?.GetDataForSave() ?? string.Empty;
@ -152,43 +138,44 @@ public class StorageCollection<T>
{ {
if (!File.Exists(filename)) if (!File.Exists(filename))
{ {
throw new Exception("Файл не существует"); throw new FileNotFoundException("Файл не существует");
} }
using (StreamReader sr = new StreamReader(filename)) using (StreamReader sr = new StreamReader(filename))
{ {
string? str; string? str;
str = sr.ReadLine(); str = sr.ReadLine();
if (str != _collectionKey.ToString()) if (str != _collectionKey.ToString()) throw new FormatException("В файле неверные данные");
throw new Exception("Не удалось преобразовать данные");
_storages.Clear(); _storages.Clear();
while ((str = sr.ReadLine()) != null) while ((str = sr.ReadLine()) != null)
{ {
string[] record = str.Split(_separatorForKeyValue); string[] record = str.Split(_separatorForKeyValue);
if (record.Length != 4) if (record.Length != 3)
{ {
continue; continue;
} }
CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]);
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType); CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(record[0]) ??
throw new Exception("Не удалось определить информацию коллекции:" + record[0]);
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionInfo.CollectionType) ??
throw new Exception("Не удалось определить тип коллекции:" + record[1]);
if (collection == null) if (collection == null)
{ {
throw new Exception("В файле нет данных"); throw new InvalidOperationException("Не удалось определить тип коллекции:" + record[1]);
} }
collection.MaxCount = Convert.ToInt32(record[2]); collection.MaxCount = Convert.ToInt32(record[1]);
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set) foreach (string elem in set)
{ {
if (elem?.CreateDrawningTruck() is T truck) if (elem?.CreateDrawningTruck() is T plane)
{ {
try try
{ {
if (collection.Insert(truck) == -1) if (collection.Insert(plane) == -1) throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]);
{
throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]);
}
} }
catch (CollectionOverflowException ex) catch (CollectionOverflowException ex)
{ {
@ -196,7 +183,7 @@ public class StorageCollection<T>
} }
} }
} }
_storages.Add(record[0], collection); _storages.Add(collectionInfo, collection);
} }
} }
} }

View File

@ -0,0 +1,34 @@
namespace ProjectCleaningCar.Drawnings;
/// <summary>
/// Сравнение по цвету, скорости, весу
/// </summary>
public class DrawningTruckCompareByColor : IComparer<DrawningTruck?>
{
public int Compare(DrawningTruck? x, DrawningTruck? y)
{
if (x == null || x.EntityTruck == null)
{
return 1;
}
if (y == null || y.EntityTruck == null)
{
return -1;
}
var bodycolorCompare = y.EntityTruck.BodyColor.Name.CompareTo(x.EntityTruck.BodyColor.Name);
if (bodycolorCompare != 0)
{
return bodycolorCompare;
}
var speedCompare = y.EntityTruck.Speed.CompareTo(x.EntityTruck.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return y.EntityTruck.Weight.CompareTo(x.EntityTruck.Weight);
}
}

View File

@ -0,0 +1,33 @@
namespace ProjectCleaningCar.Drawnings;
/// <summary>
/// Сравнение по типу, скорости, весу
/// </summary>
public class DrawningTruckCompareByType : IComparer<DrawningTruck?>
{
public int Compare(DrawningTruck? x, DrawningTruck? y)
{
if (x == null || x.EntityTruck == null)
{
return 1;
}
if (y == null || y.EntityTruck == null)
{
return -1;
}
if (x.GetType().Name != y.GetType().Name)
{
return y.GetType().Name.CompareTo(x.GetType().Name);
}
var speedCompare = y.EntityTruck.Speed.CompareTo(x.EntityTruck.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return y.EntityTruck.Weight.CompareTo(x.EntityTruck.Weight);
}
}

View File

@ -0,0 +1,66 @@
using ProjectCleaningCar.Entites;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectCleaningCar.Drawnings;
/// <summary>
/// Реализация сравнения двух объектов класса-прорисовки
/// </summary>
public class DrawiningTruckEqutables : IEqualityComparer<DrawningTruck?>
{
public bool Equals(DrawningTruck? x, DrawningTruck? y)
{
if (x == null || x.EntityTruck == null)
{
return false;
}
if (y == null || y.EntityTruck == null)
{
return false;
}
if (x.GetType().Name != y.GetType().Name)
{
return false;
}
if (x.EntityTruck.Speed != y.EntityTruck.Speed)
{
return false;
}
if (x.EntityTruck.Weight != y.EntityTruck.Weight)
{
return false;
}
if (x.EntityTruck.BodyColor != y.EntityTruck.BodyColor)
{
return false;
}
if (x is DrawningCleaningCar && y is DrawningCleaningCar)
{
EntityCleaningCar _x = (EntityCleaningCar)x.EntityTruck;
EntityCleaningCar _y = (EntityCleaningCar)x.EntityTruck;
if (_x.AdditionalColor != _y.AdditionalColor)
{
return false;
}
if (_x.WaterTank != _y.WaterTank)
{
return false;
}
if (_x.SweepingBrush != _y.SweepingBrush)
{
return false;
}
}
return true;
}
public int GetHashCode([DisallowNull] DrawningTruck obj)
{
return obj.GetHashCode();
}
}

View File

@ -1,5 +1,5 @@
using System.Runtime.Serialization; using System.Runtime.Serialization;
namespace ProjectSportCar.Exceptions; namespace ProjectCleaningCar.Exceptions;
/// <summary> /// <summary>
/// Класс, описывающий ошибку, что по указанной позиции нет элемента /// Класс, описывающий ошибку, что по указанной позиции нет элемента

View File

@ -0,0 +1,16 @@
using System.Runtime.Serialization;
namespace ProjectCleaningCar.Exceptions;
/// <summary>
/// Класс, описывающий ошибку наличия такого же объекта в коллекции
/// </summary>
[Serializable]
internal class ObjectNotUniqueException : ApplicationException
{
public ObjectNotUniqueException(int count) : base("В коллекции содержится равный элемент: " + count) { }
public ObjectNotUniqueException() : base() { }
public ObjectNotUniqueException(string message) : base(message) { }
public ObjectNotUniqueException(string message, Exception exception) : base(message, exception) { }
protected ObjectNotUniqueException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}

View File

@ -1,5 +1,5 @@
using System.Runtime.Serialization; using System.Runtime.Serialization;
namespace ProjectSportCar.Exceptions; namespace ProjectCleaningCar.Exceptions;
/// <summary> /// <summary>
/// Класс, описывающий ошибку выхода за границы коллекции /// Класс, описывающий ошибку выхода за границы коллекции

View File

@ -53,6 +53,9 @@ namespace ProjectCleaningCar
LoadToolStripMenuItem = new ToolStripMenuItem(); LoadToolStripMenuItem = new ToolStripMenuItem();
saveFileDialog = new SaveFileDialog(); saveFileDialog = new SaveFileDialog();
openFileDialog = new OpenFileDialog(); openFileDialog = new OpenFileDialog();
button1 = new Button();
buttonSortByColor = new Button();
buttonSortByType = new Button();
groupBoxTools.SuspendLayout(); groupBoxTools.SuspendLayout();
panelCompanyTools.SuspendLayout(); panelCompanyTools.SuspendLayout();
panelStorage.SuspendLayout(); panelStorage.SuspendLayout();
@ -69,13 +72,15 @@ namespace ProjectCleaningCar
groupBoxTools.Dock = DockStyle.Right; groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(927, 28); groupBoxTools.Location = new Point(927, 28);
groupBoxTools.Name = "groupBoxTools"; groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(250, 641); groupBoxTools.Size = new Size(250, 652);
groupBoxTools.TabIndex = 0; groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false; groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты"; groupBoxTools.Text = "Инструменты";
// //
// panelCompanyTools // panelCompanyTools
// //
panelCompanyTools.Controls.Add(buttonSortByType);
panelCompanyTools.Controls.Add(buttonSortByColor);
panelCompanyTools.Controls.Add(buttonAdd); panelCompanyTools.Controls.Add(buttonAdd);
panelCompanyTools.Controls.Add(maskedTextBoxPosition); panelCompanyTools.Controls.Add(maskedTextBoxPosition);
panelCompanyTools.Controls.Add(buttonRefresh); panelCompanyTools.Controls.Add(buttonRefresh);
@ -83,15 +88,15 @@ namespace ProjectCleaningCar
panelCompanyTools.Controls.Add(buttonGoToCheck); panelCompanyTools.Controls.Add(buttonGoToCheck);
panelCompanyTools.Dock = DockStyle.Bottom; panelCompanyTools.Dock = DockStyle.Bottom;
panelCompanyTools.Enabled = false; panelCompanyTools.Enabled = false;
panelCompanyTools.Location = new Point(3, 393); panelCompanyTools.Location = new Point(3, 394);
panelCompanyTools.Name = "panelCompanyTools"; panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(244, 245); panelCompanyTools.Size = new Size(244, 255);
panelCompanyTools.TabIndex = 8; panelCompanyTools.TabIndex = 8;
// //
// buttonAdd // buttonAdd
// //
buttonAdd.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; buttonAdd.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonAdd.Location = new Point(13, 3); buttonAdd.Location = new Point(15, 2);
buttonAdd.Name = "buttonAdd"; buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(220, 33); buttonAdd.Size = new Size(220, 33);
buttonAdd.TabIndex = 1; buttonAdd.TabIndex = 1;
@ -101,7 +106,7 @@ namespace ProjectCleaningCar
// //
// maskedTextBoxPosition // maskedTextBoxPosition
// //
maskedTextBoxPosition.Location = new Point(15, 98); maskedTextBoxPosition.Location = new Point(15, 42);
maskedTextBoxPosition.Mask = "00"; maskedTextBoxPosition.Mask = "00";
maskedTextBoxPosition.Name = "maskedTextBoxPosition"; maskedTextBoxPosition.Name = "maskedTextBoxPosition";
maskedTextBoxPosition.Size = new Size(220, 27); maskedTextBoxPosition.Size = new Size(220, 27);
@ -111,9 +116,9 @@ namespace ProjectCleaningCar
// buttonRefresh // buttonRefresh
// //
buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRefresh.Location = new Point(15, 201); buttonRefresh.Location = new Point(13, 149);
buttonRefresh.Name = "buttonRefresh"; buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(220, 35); buttonRefresh.Size = new Size(220, 29);
buttonRefresh.TabIndex = 6; buttonRefresh.TabIndex = 6;
buttonRefresh.Text = "Обновить"; buttonRefresh.Text = "Обновить";
buttonRefresh.UseVisualStyleBackColor = true; buttonRefresh.UseVisualStyleBackColor = true;
@ -122,7 +127,7 @@ namespace ProjectCleaningCar
// buttonRemoveTruck // buttonRemoveTruck
// //
buttonRemoveTruck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; buttonRemoveTruck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRemoveTruck.Location = new Point(15, 131); buttonRemoveTruck.Location = new Point(15, 75);
buttonRemoveTruck.Name = "buttonRemoveTruck"; buttonRemoveTruck.Name = "buttonRemoveTruck";
buttonRemoveTruck.Size = new Size(220, 31); buttonRemoveTruck.Size = new Size(220, 31);
buttonRemoveTruck.TabIndex = 4; buttonRemoveTruck.TabIndex = 4;
@ -133,7 +138,7 @@ namespace ProjectCleaningCar
// buttonGoToCheck // buttonGoToCheck
// //
buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonGoToCheck.Location = new Point(15, 168); buttonGoToCheck.Location = new Point(15, 112);
buttonGoToCheck.Name = "buttonGoToCheck"; buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(220, 31); buttonGoToCheck.Size = new Size(220, 31);
buttonGoToCheck.TabIndex = 5; buttonGoToCheck.TabIndex = 5;
@ -250,7 +255,7 @@ namespace ProjectCleaningCar
pictureBox.Dock = DockStyle.Fill; pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 28); pictureBox.Location = new Point(0, 28);
pictureBox.Name = "pictureBox"; pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(927, 641); pictureBox.Size = new Size(927, 652);
pictureBox.TabIndex = 1; pictureBox.TabIndex = 1;
pictureBox.TabStop = false; pictureBox.TabStop = false;
// //
@ -295,12 +300,45 @@ namespace ProjectCleaningCar
// //
openFileDialog.Filter = "txt file | *.txt"; openFileDialog.Filter = "txt file | *.txt";
// //
// button1
//
button1.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
button1.Location = new Point(728, 584);
button1.Name = "button1";
button1.Size = new Size(0, 29);
button1.TabIndex = 7;
button1.Text = "Обновить";
button1.UseVisualStyleBackColor = true;
//
// buttonSortByColor
//
buttonSortByColor.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonSortByColor.Location = new Point(15, 217);
buttonSortByColor.Name = "buttonSortByColor";
buttonSortByColor.Size = new Size(220, 29);
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(15, 184);
buttonSortByType.Name = "buttonSortByType";
buttonSortByType.Size = new Size(220, 29);
buttonSortByType.TabIndex = 9;
buttonSortByType.Text = "Сортировка по типу";
buttonSortByType.UseVisualStyleBackColor = true;
buttonSortByType.Click += buttonSortByType_Click;
//
// FormTruckCollection // FormTruckCollection
// //
AutoScaleDimensions = new SizeF(8F, 20F); AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font; AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1177, 669); ClientSize = new Size(1177, 680);
Controls.Add(pictureBox); Controls.Add(pictureBox);
Controls.Add(button1);
Controls.Add(groupBoxTools); Controls.Add(groupBoxTools);
Controls.Add(menuStrip); Controls.Add(menuStrip);
MainMenuStrip = menuStrip; MainMenuStrip = menuStrip;
@ -344,5 +382,8 @@ namespace ProjectCleaningCar
private ToolStripMenuItem LoadToolStripMenuItem; private ToolStripMenuItem LoadToolStripMenuItem;
private SaveFileDialog saveFileDialog; private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog; private OpenFileDialog openFileDialog;
private Button buttonSortByType;
private Button buttonSortByColor;
private Button button1;
} }
} }

View File

@ -2,9 +2,6 @@
using ProjectCleaningCar.CollectionGenericObjects; using ProjectCleaningCar.CollectionGenericObjects;
using ProjectCleaningCar.Drawnings; using ProjectCleaningCar.Drawnings;
using ProjectCleaningCar.Exceptions; using ProjectCleaningCar.Exceptions;
using ProjectSportCar.Exceptions;
using System.Numerics;
using System.Windows.Forms;
namespace ProjectCleaningCar; namespace ProjectCleaningCar;
/// <summary> /// <summary>
@ -227,10 +224,10 @@ public partial class FormTruckCollection : Form
listBoxCollection.Items.Clear(); listBoxCollection.Items.Clear();
for (int i = 0; i < _storageCollection.Keys?.Count; ++i) for (int i = 0; i < _storageCollection.Keys?.Count; ++i)
{ {
string? colName = _storageCollection.Keys?[i]; string? name = _storageCollection.Keys?[i].Name;
if (!string.IsNullOrEmpty(colName)) if (!string.IsNullOrEmpty(name))
{ {
listBoxCollection.Items.Add(colName); listBoxCollection.Items.Add(name);
} }
} }
} }
@ -307,4 +304,37 @@ public partial class FormTruckCollection : Form
} }
} }
} }
/// <summary>
/// Сортировка по типу
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonSortByType_Click(object sender, EventArgs e)
{
CompareTrucks(new DrawningTruckCompareByType());
}
/// <summary>
/// Сортировка по цвету
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonSortByColor_Click(object sender, EventArgs e)
{
CompareTrucks(new DrawningTruckCompareByColor());
}
/// <summary>
/// Сортировка по сравнителю
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
private void CompareTrucks(IComparer<DrawningTruck?> comparer)
{
if (_company == null)
{
return;
}
_company.Sort(comparer);
pictureBox.Image = _company.Show();
}
} }