Pibd_13_Fathutdinov_A.I. labWork_08 Simple #9
@ -60,9 +60,9 @@ namespace ProjectLiner.CollectionGenericObjects
|
||||
/// <param name="company">Компания</param>
|
||||
/// <param name="airplane">Добавляемый объект</param>
|
||||
/// <returns></returns>
|
||||
public static int operator +(AbstractCompany company, DrawningCommonLiner airplane)
|
||||
public static int operator +(AbstractCompany company, DrawningCommonLiner liner)
|
||||
{
|
||||
return company._collection.Insert(airplane);
|
||||
return company._collection.Insert(liner, new DrawningLinerEqutables() );
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@ -130,5 +130,11 @@ namespace ProjectLiner.CollectionGenericObjects
|
||||
/// Расстановка объектов
|
||||
/// </summary>
|
||||
protected abstract void SetObjectsPosition();
|
||||
|
||||
/// <summary>
|
||||
/// Сортировка коллекции
|
||||
/// </summary>
|
||||
/// <param name="comparer">Сравнитель объектов</param>
|
||||
public void Sort(IComparer<DrawningCommonLiner?> comparer) => _collection?.CollectionSort(comparer);
|
||||
}
|
||||
}
|
@ -0,0 +1,74 @@
|
||||
using ProjectLiner.CollectionGenericObjects;
|
||||
|
||||
namespace ProjectLiner.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();
|
||||
}
|
||||
}
|
@ -21,16 +21,18 @@
|
||||
/// Добавление объекта в коллекцию
|
||||
/// </summary>
|
||||
/// <param name="obj">Добавляемый объект</param>
|
||||
/// /// <param name="comparer">Сравнение двух объектов</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">Сравнение двух объектов</param>
|
||||
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
|
||||
int Insert(T obj, int position);
|
||||
int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null);
|
||||
|
||||
/// <summary>
|
||||
/// Удаление объекта из коллекции с конкретной позиции
|
||||
@ -56,5 +58,11 @@
|
||||
/// </summary>
|
||||
/// <returns>Поэлементый вывод элементов коллекции</returns>
|
||||
IEnumerable<T?> GetItems();
|
||||
|
||||
/// <summary>
|
||||
/// Сортировка коллекции
|
||||
/// </summary>
|
||||
/// <param name="comparer"></param>
|
||||
void CollectionSort(IComparer<T?> comparer);
|
||||
}
|
||||
}
|
@ -58,20 +58,31 @@ namespace ProjectLiner.CollectionGenericObjects
|
||||
return _collection[position];
|
||||
}
|
||||
|
||||
public int Insert(T obj)
|
||||
public int Insert(T obj, IEqualityComparer<T?>? comparer = null)
|
||||
{
|
||||
if (Count >= _maxCount)
|
||||
throw new CollectionOverflowException(Count);
|
||||
if (Count == _maxCount) throw new CollectionOverflowException();
|
||||
if (comparer != null)
|
||||
{
|
||||
if (_collection.Contains(obj, comparer))
|
||||
{
|
||||
throw new ObjectAlreadyExistsException(obj);
|
||||
}
|
||||
}
|
||||
_collection.Add(obj);
|
||||
return Count;
|
||||
}
|
||||
|
||||
public int Insert(T obj, int position)
|
||||
public int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
|
||||
{
|
||||
if (Count == _maxCount)
|
||||
throw new CollectionOverflowException(Count);
|
||||
if (position < 0 || position > Count)
|
||||
throw new PositionOutOfCollectionException(position); ;
|
||||
if (Count == _maxCount) throw new CollectionOverflowException();
|
||||
if (position >= Count || position < 0) throw new PositionOutOfCollectionException();
|
||||
if (comparer != null)
|
||||
{
|
||||
if (_collection.Contains(obj, comparer))
|
||||
{
|
||||
throw new ObjectAlreadyExistsException(obj);
|
||||
}
|
||||
}
|
||||
_collection.Insert(position, obj);
|
||||
return position;
|
||||
}
|
||||
@ -93,5 +104,10 @@ namespace ProjectLiner.CollectionGenericObjects
|
||||
yield return _collection[i];
|
||||
}
|
||||
}
|
||||
|
||||
public void CollectionSort(IComparer<T?> comparer)
|
||||
{
|
||||
_collection.Sort(comparer);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -61,8 +61,18 @@ namespace ProjectLiner.CollectionGenericObjects
|
||||
return _collection[position];
|
||||
}
|
||||
|
||||
public int Insert(T obj)
|
||||
public int Insert(T obj, IEqualityComparer<T?>? comparer = null)
|
||||
{
|
||||
if (comparer != null)
|
||||
{
|
||||
foreach (T? i in _collection)
|
||||
{
|
||||
if (comparer.Equals(i, obj))
|
||||
{
|
||||
throw new ObjectAlreadyExistsException(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (int i = 0; i < Count; i++)
|
||||
{
|
||||
if (_collection[i] == null)
|
||||
@ -71,20 +81,29 @@ namespace ProjectLiner.CollectionGenericObjects
|
||||
return i;
|
||||
}
|
||||
}
|
||||
throw new CollectionOverflowException(Count);
|
||||
throw new CollectionOverflowException();
|
||||
}
|
||||
|
||||
public int Insert(T obj, int position)
|
||||
public int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
|
||||
{
|
||||
if (position >= Count || position < 0)
|
||||
throw new PositionOutOfCollectionException(position);
|
||||
if (position >= Count || position < 0) throw new PositionOutOfCollectionException();
|
||||
|
||||
if (comparer != null)
|
||||
{
|
||||
foreach (T? i in _collection)
|
||||
{
|
||||
if (comparer.Equals(i, obj))
|
||||
{
|
||||
throw new ObjectAlreadyExistsException(position);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (_collection[position] == null)
|
||||
{
|
||||
_collection[position] = obj;
|
||||
return position;
|
||||
}
|
||||
|
||||
int temp = position + 1;
|
||||
while (temp < Count)
|
||||
{
|
||||
@ -93,21 +112,19 @@ namespace ProjectLiner.CollectionGenericObjects
|
||||
_collection[temp] = obj;
|
||||
return temp;
|
||||
}
|
||||
temp++;
|
||||
++temp;
|
||||
}
|
||||
|
||||
temp = position - 1;
|
||||
while (temp > 0)
|
||||
while (temp >= 0)
|
||||
{
|
||||
if (_collection[temp] == null)
|
||||
{
|
||||
_collection[temp] = obj;
|
||||
return temp;
|
||||
}
|
||||
temp--;
|
||||
--temp;
|
||||
}
|
||||
|
||||
throw new CollectionOverflowException(Count);
|
||||
throw new CollectionOverflowException();
|
||||
}
|
||||
|
||||
public T? Remove(int position)
|
||||
@ -130,5 +147,9 @@ namespace ProjectLiner.CollectionGenericObjects
|
||||
yield return _collection[i];
|
||||
}
|
||||
}
|
||||
public void CollectionSort(IComparer<T?> comparer)
|
||||
{
|
||||
Array.Sort(_collection, comparer);
|
||||
}
|
||||
}
|
||||
}
|
@ -1,226 +1,223 @@
|
||||
using System.Data;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
|
||||
using ProjectLiner.CollectionGenericObjects;
|
||||
using ProjectLiner.Drawnings;
|
||||
using ProjectLiner.Exceptions;
|
||||
using ProjectLiner.CollectionGenericObjects;
|
||||
using ProjectLiner.Exceptions;
|
||||
using System.Data;
|
||||
using System.Text;
|
||||
using System.Xml.Linq;
|
||||
|
||||
namespace ProjectLiner.CollectionGenericObjects
|
||||
namespace ProjectLiner.CollectionGenericObjects;
|
||||
|
||||
/// <summary>
|
||||
/// Класс-хранилище коллекций
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
public class StorageCollection<T>
|
||||
where T : DrawningCommonLiner
|
||||
{
|
||||
/// <summary>
|
||||
/// Класс-хранилище коллекций
|
||||
/// Словарь (хранилище) с коллекциями
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
public class StorageCollection<T>
|
||||
where T : DrawningCommonLiner
|
||||
readonly Dictionary<CollectionInfo, ICollectionGenericObjects<T>> _storages;
|
||||
|
||||
/// <summary>
|
||||
/// Ключевое слово, с которого должен начинаться файл
|
||||
/// </summary>
|
||||
private readonly string _collectionKey = "CollectionsStorage";
|
||||
|
||||
/// <summary>
|
||||
/// Разделитель для записей коллекции данных в файл
|
||||
/// </summary>
|
||||
private readonly string _separatorItems = ";";
|
||||
|
||||
/// <summary>
|
||||
/// Разделитель для записи ключа и значения элемента словаря
|
||||
/// </summary>
|
||||
private readonly string _separatorForKeyValue = "|";
|
||||
|
||||
/// <summary>
|
||||
/// Возвращение списка названий коллекций
|
||||
/// </summary>
|
||||
public List<CollectionInfo> Keys => _storages.Keys.ToList();
|
||||
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
/// </summary>
|
||||
public StorageCollection()
|
||||
{
|
||||
/// <summary>
|
||||
/// Словарь (хранилище) с коллекциями
|
||||
/// </summary>
|
||||
readonly Dictionary<string, ICollectionGenericObjects<T>> _storages;
|
||||
|
||||
/// <summary>
|
||||
/// Возвращение списка названий коллекций
|
||||
/// </summary>
|
||||
public List<string> Keys => _storages.Keys.ToList();
|
||||
|
||||
/// <summary>
|
||||
/// Ключевое слово, с которого должен начинаться файл
|
||||
/// </summary>
|
||||
private readonly string _collectionKey = "CollectionsStorage";
|
||||
|
||||
/// <summary>
|
||||
/// Разделитель для записи ключа и значения элемента словаря
|
||||
/// </summary>
|
||||
private readonly string _separatorForKeyValue = "|";
|
||||
|
||||
/// <summary>
|
||||
/// Разделитель для записей коллекции данных в файл
|
||||
/// </summary>
|
||||
private readonly string _separatorItems = ";";
|
||||
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
/// </summary>
|
||||
public StorageCollection()
|
||||
_storages = new Dictionary<CollectionInfo, ICollectionGenericObjects<T>>();
|
||||
}
|
||||
/// <summary>
|
||||
/// Добавление коллекции в хранилище
|
||||
/// </summary>
|
||||
/// <param name="name">Название коллекции</param>
|
||||
/// <param name="collectionType">тип коллекции</param>
|
||||
public void AddCollection(string name, CollectionType collectionType)
|
||||
{
|
||||
CollectionInfo collectionInfo = new(name, collectionType, string.Empty);
|
||||
if (name == null || _storages.ContainsKey(collectionInfo))
|
||||
return;
|
||||
switch (collectionType)
|
||||
{
|
||||
_storages = new Dictionary<string, ICollectionGenericObjects<T>>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Добавление коллекции в хранилище
|
||||
/// </summary>
|
||||
/// <param name="name">Название коллекции</param>
|
||||
/// <param name="collectionType">тип коллекции</param>
|
||||
public void AddCollection(string name, CollectionType collectionType)
|
||||
{
|
||||
if (name == null || _storages.ContainsKey(name))
|
||||
case CollectionType.None:
|
||||
return;
|
||||
|
||||
switch (collectionType)
|
||||
{
|
||||
case CollectionType.None:
|
||||
return;
|
||||
case CollectionType.Massive:
|
||||
_storages[name] = new MassiveGenericObjects<T>();
|
||||
return;
|
||||
case CollectionType.List:
|
||||
_storages[name] = new ListGenericObjects<T>();
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Удаление коллекции
|
||||
/// </summary>
|
||||
/// <param name="name">Название коллекции</param>
|
||||
public void DelCollection(string name)
|
||||
{
|
||||
if (_storages.ContainsKey(name))
|
||||
_storages.Remove(name);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Доступ к коллекции
|
||||
/// </summary>
|
||||
/// <param name="name">Название коллекции</param>
|
||||
/// <returns></returns>
|
||||
public ICollectionGenericObjects<T>? this[string name]
|
||||
{
|
||||
get
|
||||
{
|
||||
if (name == null || !_storages.ContainsKey(name))
|
||||
return null;
|
||||
|
||||
return _storages[name];
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Сохранение информации по самолетам в хранилище в файл
|
||||
/// </summary>
|
||||
/// <param name="filename">Путь и имя файла</param>
|
||||
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
|
||||
public void SaveData(string filename)
|
||||
{
|
||||
if (_storages.Count == 0)
|
||||
throw new NullReferenceException("В хранилище отсутствуют коллекции для сохранения");
|
||||
|
||||
if (File.Exists(filename))
|
||||
File.Delete(filename);
|
||||
|
||||
|
||||
using (StreamWriter sw = new(filename))
|
||||
{
|
||||
sw.Write(_collectionKey);
|
||||
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages)
|
||||
{
|
||||
sw.Write(Environment.NewLine);
|
||||
if (value.Value.Count == 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
sw.Write(value.Key);
|
||||
sw.Write(_separatorForKeyValue);
|
||||
sw.Write(value.Value.GetCollectionType);
|
||||
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;
|
||||
}
|
||||
|
||||
sw.Write(data);
|
||||
sw.Write(_separatorItems);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Загрузка информации по самолетам в хранилище из файла
|
||||
/// </summary>
|
||||
/// <param name="filename">Путь и имя файла</param>
|
||||
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
|
||||
public void LoadData(string filename)
|
||||
{
|
||||
if (!File.Exists(filename))
|
||||
{
|
||||
throw new FileNotFoundException("Файл не существует");
|
||||
}
|
||||
|
||||
using (StreamReader sr = new(filename))
|
||||
{
|
||||
string str = sr.ReadLine();
|
||||
if (str == null || str.Length == 0)
|
||||
{
|
||||
throw new FileFormatException("В файле нет данных");
|
||||
}
|
||||
|
||||
if (!str.Equals(_collectionKey))
|
||||
{
|
||||
throw new FileFormatException("В файле неверные данные");
|
||||
}
|
||||
_storages.Clear();
|
||||
|
||||
while (!sr.EndOfStream)
|
||||
{
|
||||
string[] record = sr.ReadLine().Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
|
||||
if (record.Length != 4)
|
||||
{
|
||||
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);
|
||||
foreach (string elem in set)
|
||||
{
|
||||
if (elem?.CreateDrawningCommonLiner() is T airplane)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (collection.Insert(airplane) == -1)
|
||||
throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]);
|
||||
}
|
||||
catch (CollectionOverflowException ex)
|
||||
{
|
||||
throw new OverflowException("Коллекция переполнена", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
_storages.Add(record[0], collection);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Создание коллекции по типу
|
||||
/// </summary>
|
||||
/// <param name="collectionType"></param>
|
||||
/// <returns></returns>
|
||||
private static ICollectionGenericObjects<T>? CreateCollection(CollectionType collectionType)
|
||||
{
|
||||
return collectionType switch
|
||||
{
|
||||
CollectionType.Massive => new MassiveGenericObjects<T>(),
|
||||
CollectionType.List => new ListGenericObjects<T>(),
|
||||
_ => null,
|
||||
};
|
||||
case CollectionType.Massive:
|
||||
_storages[collectionInfo] = new MassiveGenericObjects<T>();
|
||||
return;
|
||||
case CollectionType.List:
|
||||
_storages[collectionInfo] = new ListGenericObjects<T>();
|
||||
return;
|
||||
default: break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Удаление коллекции
|
||||
/// </summary>
|
||||
/// <param name="name">Название коллекции</param>
|
||||
public void DelCollection(string name)
|
||||
{
|
||||
CollectionInfo collectionInfo = new(name, CollectionType.None, string.Empty);
|
||||
if (_storages.ContainsKey(collectionInfo))
|
||||
_storages.Remove(collectionInfo);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Доступ к коллекции
|
||||
/// </summary>
|
||||
/// <param name="name">Название коллекции</param>
|
||||
/// <returns></returns>
|
||||
public ICollectionGenericObjects<T>? this[string name]
|
||||
{
|
||||
get
|
||||
{
|
||||
CollectionInfo collectionInfo = new(name, CollectionType.None, string.Empty);
|
||||
if (_storages.ContainsKey(collectionInfo))
|
||||
return _storages[collectionInfo];
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Сохранение информации по автомобилям в хранилище в файл
|
||||
/// </summary>
|
||||
/// <param name="filename"></param>
|
||||
/// <returns></returns>
|
||||
public void SaveData(string filename)
|
||||
{
|
||||
if (_storages.Count == 0)
|
||||
{
|
||||
throw new InvalidDataException("В хранилище отсутствуют коллекции для сохранения");
|
||||
|
||||
}
|
||||
if (File.Exists(filename))
|
||||
{
|
||||
File.Delete(filename);
|
||||
}
|
||||
using (StreamWriter writer = new(filename))
|
||||
{
|
||||
writer.Write(_collectionKey);
|
||||
foreach (KeyValuePair<CollectionInfo, ICollectionGenericObjects<T>> value in _storages)
|
||||
{
|
||||
writer.Write(Environment.NewLine);
|
||||
// не сохраняем пустые коллекции
|
||||
if (value.Value.Count == 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
writer.Write(value.Key);
|
||||
writer.Write(_separatorForKeyValue);
|
||||
writer.Write(value.Value.MaxCount);
|
||||
writer.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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Загрузка информации по автомобилям в хранилище из файла
|
||||
/// </summary>
|
||||
/// <param name="filename">>Путь и имя файла</param>
|
||||
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
|
||||
public void LoadData(string filename)
|
||||
{
|
||||
if (!File.Exists(filename))
|
||||
{
|
||||
throw new FileNotFoundException($"{filename} не существует");
|
||||
}
|
||||
using (StreamReader reader = new(filename))
|
||||
{
|
||||
string line = reader.ReadLine();
|
||||
if (line == null || line.Length == 0)
|
||||
{
|
||||
throw new FileFormatException("Файл не подходит");
|
||||
}
|
||||
if (!line.Equals(_collectionKey))
|
||||
{
|
||||
|
||||
throw new IOException("В файле неверные данные");
|
||||
}
|
||||
_storages.Clear();
|
||||
while ((line = reader.ReadLine()) != null)
|
||||
{
|
||||
string[] record = line.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
|
||||
if (record.Length != 3)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(record[0]) ?? throw new Exception("Не удалось определить информацию коллекции" + record[0]);
|
||||
|
||||
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionInfo.CollectionType);
|
||||
if (collection == null)
|
||||
{
|
||||
throw new InvalidOperationException("Не удалось создать коллекцию");
|
||||
}
|
||||
collection.MaxCount = Convert.ToInt32(record[1]);
|
||||
string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
|
||||
foreach (string elem in set)
|
||||
{
|
||||
if (elem?.CreateDrawningCommonLiner() is T truck)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (collection.Insert(truck) == -1)
|
||||
{
|
||||
throw new ConstraintException("Объект не удалось добавить в коллекцию: " + record[3]);
|
||||
}
|
||||
}
|
||||
catch (CollectionOverflowException ex)
|
||||
{
|
||||
throw new DataException("Коллекция переполнена", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
_storages.Add(collectionInfo, collection);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Создание коллекции по типу
|
||||
/// </summary>
|
||||
/// <param name="collectionType"></param>
|
||||
/// <returns></returns>
|
||||
private static ICollectionGenericObjects<T>? CreateCollection(CollectionType collectionType)
|
||||
{
|
||||
return collectionType switch
|
||||
{
|
||||
CollectionType.Massive => new MassiveGenericObjects<T>(),
|
||||
CollectionType.List => new ListGenericObjects<T>(),
|
||||
_ => null,
|
||||
};
|
||||
}
|
||||
}
|
@ -0,0 +1,38 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace ProjectLiner.Drawnings;
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Сравнение по цвету, скорости, весу
|
||||
/// </summary>
|
||||
public class DrawningLinerCompareByColor : IComparer<DrawningCommonLiner?>
|
||||
{
|
||||
public int Compare(DrawningCommonLiner? x, DrawningCommonLiner? y)
|
||||
{
|
||||
if (x == null || x.EntityCommonLiner == null)
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (y == null || y.EntityCommonLiner == null)
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
var bodycolorCompare = x.EntityCommonLiner.BodyColor.Name.CompareTo(y.EntityCommonLiner.BodyColor.Name);
|
||||
if (bodycolorCompare != 0)
|
||||
{
|
||||
return bodycolorCompare;
|
||||
}
|
||||
var speedCompare = x.EntityCommonLiner.Speed.CompareTo(y.EntityCommonLiner.Speed);
|
||||
if (speedCompare != 0)
|
||||
{
|
||||
return speedCompare;
|
||||
}
|
||||
return x.EntityCommonLiner.Weight.CompareTo(y.EntityCommonLiner.Weight);
|
||||
}
|
||||
}
|
@ -0,0 +1,40 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace ProjectLiner.Drawnings;
|
||||
/// <summary>
|
||||
/// Сравнение по типу, скорости, весу
|
||||
/// </summary>
|
||||
public class DrawningLinerCompareByType : IComparer<DrawningCommonLiner?>
|
||||
{
|
||||
|
||||
public int Compare(DrawningCommonLiner? x, DrawningCommonLiner? y)
|
||||
{
|
||||
if (x == null && y == null) return 0;
|
||||
if (x == null || x.EntityCommonLiner == null)
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (y == null || y.EntityCommonLiner == null)
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
|
||||
if (x.GetType().Name != y.GetType().Name)
|
||||
{
|
||||
return x.GetType().Name.CompareTo(y.GetType().Name);
|
||||
}
|
||||
|
||||
var speedCompare = x.EntityCommonLiner.Speed.CompareTo(y.EntityCommonLiner.Speed);
|
||||
if (speedCompare != 0)
|
||||
{
|
||||
return speedCompare;
|
||||
}
|
||||
|
||||
return x.EntityCommonLiner.Weight.CompareTo(y.EntityCommonLiner.Weight);
|
||||
}
|
||||
}
|
@ -0,0 +1,71 @@
|
||||
using ProjectLiner.Drawnings;
|
||||
using ProjectLiner.Entities;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
/// <summary>
|
||||
/// Реализация сравнения двух объектов класса-прорисовки
|
||||
/// </summary>
|
||||
public class DrawningLinerEqutables : IEqualityComparer<DrawningCommonLiner?>
|
||||
{
|
||||
public bool Equals(DrawningCommonLiner x, DrawningCommonLiner? y)
|
||||
{
|
||||
if (x == null || x.EntityCommonLiner == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (y == null || y.EntityCommonLiner == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (x.GetType().Name != y.GetType().Name)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (x.EntityCommonLiner.Speed != y.EntityCommonLiner.Speed)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (x.EntityCommonLiner.Weight != y.EntityCommonLiner.Weight)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (x.EntityCommonLiner.BodyColor != y.EntityCommonLiner.BodyColor)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (x is DrawningLiner && y is DrawningLiner)
|
||||
{
|
||||
if (((EntityLiner)x.EntityCommonLiner).AdditionalColor !=
|
||||
|
||||
((EntityLiner)y.EntityCommonLiner).AdditionalColor)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (((EntityLiner)x.EntityCommonLiner).Boats !=
|
||||
((EntityLiner)y.EntityCommonLiner).Boats)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (((EntityLiner)x.EntityCommonLiner).Anchor !=
|
||||
((EntityLiner)y.EntityCommonLiner).Anchor)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (((EntityLiner)x.EntityCommonLiner).Pipe !=
|
||||
((EntityLiner)y.EntityCommonLiner).Pipe)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public int GetHashCode([DisallowNull] DrawningCommonLiner obj)
|
||||
{
|
||||
return obj.GetHashCode();
|
||||
}
|
||||
}
|
@ -0,0 +1,22 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Runtime.Serialization;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace ProjectLiner.Exceptions;
|
||||
|
||||
/// <summary>
|
||||
/// Класс, описывающий ошибку, что в коллекции уже есть такой элемент
|
||||
/// </summary>
|
||||
[Serializable]
|
||||
public class ObjectAlreadyExistsException : ApplicationException
|
||||
{
|
||||
public ObjectAlreadyExistsException(object i) : base("В коллекции уже есть такой элемент " + i) { }
|
||||
public ObjectAlreadyExistsException() : base() { }
|
||||
public ObjectAlreadyExistsException(string message) : base(message) { }
|
||||
public ObjectAlreadyExistsException(string message, Exception exception) : base(message, exception)
|
||||
{ }
|
||||
protected ObjectAlreadyExistsException(SerializationInfo info, StreamingContext context) : base(info, context) { }
|
||||
}
|
@ -52,6 +52,8 @@
|
||||
loadToolStripMenuItem = new ToolStripMenuItem();
|
||||
openFileDialog = new OpenFileDialog();
|
||||
saveFileDialog = new SaveFileDialog();
|
||||
buttonSortByColor = new Button();
|
||||
buttonSortByType = new Button();
|
||||
groupBoxTools.SuspendLayout();
|
||||
panelStorage.SuspendLayout();
|
||||
((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit();
|
||||
@ -67,7 +69,7 @@
|
||||
groupBoxTools.Dock = DockStyle.Right;
|
||||
groupBoxTools.Location = new Point(1052, 49);
|
||||
groupBoxTools.Name = "groupBoxTools";
|
||||
groupBoxTools.Size = new Size(272, 1014);
|
||||
groupBoxTools.Size = new Size(272, 1140);
|
||||
groupBoxTools.TabIndex = 0;
|
||||
groupBoxTools.TabStop = false;
|
||||
groupBoxTools.Text = "Инструменты";
|
||||
@ -190,7 +192,7 @@
|
||||
//
|
||||
pictureBox.Dock = DockStyle.Bottom;
|
||||
pictureBox.Enabled = false;
|
||||
pictureBox.Location = new Point(0, 51);
|
||||
pictureBox.Location = new Point(0, 177);
|
||||
pictureBox.Name = "pictureBox";
|
||||
pictureBox.Size = new Size(1052, 1012);
|
||||
pictureBox.TabIndex = 1;
|
||||
@ -199,6 +201,8 @@
|
||||
// panelCompanyTools
|
||||
//
|
||||
panelCompanyTools.BackColor = SystemColors.Window;
|
||||
panelCompanyTools.Controls.Add(buttonSortByColor);
|
||||
panelCompanyTools.Controls.Add(buttonSortByType);
|
||||
panelCompanyTools.Controls.Add(buttonAddLiner);
|
||||
panelCompanyTools.Controls.Add(maskedTextBox1);
|
||||
panelCompanyTools.Controls.Add(button5);
|
||||
@ -207,14 +211,14 @@
|
||||
panelCompanyTools.Location = new Point(1052, 592);
|
||||
panelCompanyTools.Margin = new Padding(5);
|
||||
panelCompanyTools.Name = "panelCompanyTools";
|
||||
panelCompanyTools.Size = new Size(272, 470);
|
||||
panelCompanyTools.Size = new Size(272, 589);
|
||||
panelCompanyTools.TabIndex = 9;
|
||||
//
|
||||
// buttonAddLiner
|
||||
//
|
||||
buttonAddLiner.Location = new Point(6, 54);
|
||||
buttonAddLiner.Name = "buttonAddLiner";
|
||||
buttonAddLiner.Size = new Size(214, 75);
|
||||
buttonAddLiner.Size = new Size(242, 75);
|
||||
buttonAddLiner.TabIndex = 7;
|
||||
buttonAddLiner.Text = "Добавить";
|
||||
buttonAddLiner.UseVisualStyleBackColor = true;
|
||||
@ -225,7 +229,7 @@
|
||||
maskedTextBox1.Location = new Point(3, 167);
|
||||
maskedTextBox1.Mask = "00";
|
||||
maskedTextBox1.Name = "maskedTextBox1";
|
||||
maskedTextBox1.Size = new Size(217, 47);
|
||||
maskedTextBox1.Size = new Size(245, 47);
|
||||
maskedTextBox1.TabIndex = 3;
|
||||
maskedTextBox1.ValidatingType = typeof(int);
|
||||
//
|
||||
@ -234,7 +238,7 @@
|
||||
button5.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
|
||||
button5.Location = new Point(3, 384);
|
||||
button5.Name = "button5";
|
||||
button5.Size = new Size(216, 75);
|
||||
button5.Size = new Size(245, 75);
|
||||
button5.TabIndex = 6;
|
||||
button5.Text = "Обновить";
|
||||
button5.UseVisualStyleBackColor = true;
|
||||
@ -245,7 +249,7 @@
|
||||
button3.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
|
||||
button3.Location = new Point(3, 220);
|
||||
button3.Name = "button3";
|
||||
button3.Size = new Size(216, 75);
|
||||
button3.Size = new Size(245, 75);
|
||||
button3.TabIndex = 4;
|
||||
button3.Text = "Удаление Лайнера";
|
||||
button3.UseVisualStyleBackColor = true;
|
||||
@ -256,7 +260,7 @@
|
||||
button4.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
|
||||
button4.Location = new Point(3, 302);
|
||||
button4.Name = "button4";
|
||||
button4.Size = new Size(216, 75);
|
||||
button4.Size = new Size(245, 75);
|
||||
button4.TabIndex = 5;
|
||||
button4.Text = "Передать на тесты";
|
||||
button4.UseVisualStyleBackColor = true;
|
||||
@ -304,11 +308,35 @@
|
||||
//
|
||||
saveFileDialog.Filter = "txt file | *.txt";
|
||||
//
|
||||
// buttonSortByColor
|
||||
//
|
||||
buttonSortByColor.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
|
||||
buttonSortByColor.Font = new Font("Segoe UI", 9.818182F, FontStyle.Regular, GraphicsUnit.Point);
|
||||
buttonSortByColor.Location = new Point(3, 526);
|
||||
buttonSortByColor.Name = "buttonSortByColor";
|
||||
buttonSortByColor.Size = new Size(245, 44);
|
||||
buttonSortByColor.TabIndex = 9;
|
||||
buttonSortByColor.Text = "Сортировка по цвету";
|
||||
buttonSortByColor.UseVisualStyleBackColor = true;
|
||||
buttonSortByColor.Click += buttonSortByColor_Click;
|
||||
//
|
||||
// buttonSortByType
|
||||
//
|
||||
buttonSortByType.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
|
||||
buttonSortByType.Font = new Font("Segoe UI", 9.818182F, FontStyle.Regular, GraphicsUnit.Point);
|
||||
buttonSortByType.Location = new Point(4, 476);
|
||||
buttonSortByType.Name = "buttonSortByType";
|
||||
buttonSortByType.Size = new Size(244, 44);
|
||||
buttonSortByType.TabIndex = 8;
|
||||
buttonSortByType.Text = "Сортировка по типу";
|
||||
buttonSortByType.UseVisualStyleBackColor = true;
|
||||
buttonSortByType.Click += buttonSortByType_Click;
|
||||
//
|
||||
// FormLinerCollection
|
||||
//
|
||||
AutoScaleDimensions = new SizeF(17F, 41F);
|
||||
AutoScaleMode = AutoScaleMode.Font;
|
||||
ClientSize = new Size(1324, 1063);
|
||||
ClientSize = new Size(1324, 1189);
|
||||
Controls.Add(panelCompanyTools);
|
||||
Controls.Add(pictureBox);
|
||||
Controls.Add(groupBoxTools);
|
||||
@ -358,5 +386,7 @@
|
||||
private ToolStripMenuItem loadToolStripMenuItem;
|
||||
private OpenFileDialog openFileDialog;
|
||||
private SaveFileDialog saveFileDialog;
|
||||
private Button buttonSortByColor;
|
||||
private Button buttonSortByType;
|
||||
}
|
||||
}
|
@ -86,6 +86,11 @@ namespace ProjectLiner
|
||||
MessageBox.Show(ex.Message);
|
||||
_logger.LogError("Ошибка: {Message}", ex.Message);
|
||||
}
|
||||
catch (ObjectAlreadyExistsException ex)
|
||||
{
|
||||
MessageBox.Show("Такой объект есть в коллекции");
|
||||
_logger.LogWarning($"Добавление существующего объекта: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@ -240,7 +245,7 @@ namespace ProjectLiner
|
||||
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);
|
||||
}
|
||||
@ -325,5 +330,32 @@ namespace ProjectLiner
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Сортировка по типу
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
private void buttonSortByType_Click(object sender, EventArgs e) => CompareTrucks(new DrawningLinerCompareByType());
|
||||
|
||||
/// <summary>
|
||||
/// Сортировка по цвету
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
private void buttonSortByColor_Click(object sender, EventArgs e) => CompareTrucks(new DrawningLinerCompareByColor());
|
||||
|
||||
/// <summary>
|
||||
/// Сортировка по сравнителю
|
||||
/// </summary>
|
||||
private void CompareTrucks(IComparer<DrawningCommonLiner?> comparer)
|
||||
{
|
||||
if (_company == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
_company.Sort(comparer);
|
||||
pictureBox.Image = _company.Show();
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user
Зачем неоднократные преобразования, что мешает сделать это один раз?