diff --git a/ProjectElectricLocomotive/ProjectElectricLocomotive/CollectionGenericObjects/AbstractCompany.cs b/ProjectElectricLocomotive/ProjectElectricLocomotive/CollectionGenericObjects/AbstractCompany.cs index e64da79..24c5cc2 100644 --- a/ProjectElectricLocomotive/ProjectElectricLocomotive/CollectionGenericObjects/AbstractCompany.cs +++ b/ProjectElectricLocomotive/ProjectElectricLocomotive/CollectionGenericObjects/AbstractCompany.cs @@ -59,9 +59,9 @@ public abstract class AbstractCompany /// Компания /// Добавляемый объект /// - public static int operator +(AbstractCompany company, DrawningLocomotive truck) + public static int operator +(AbstractCompany company, DrawningLocomotive locomotive) { - return company._collection.Insert(truck); + return company._collection.Insert(locomotive, new DrawningLocomotiveEqutables()); } // @@ -109,7 +109,10 @@ public abstract class AbstractCompany } return bitmap; } - + /// Сортировка + /// + /// Сравнитель объектов + public void Sort(IComparer comparer) => _collection?.CollectionSort(comparer); /// /// Вывод заднего фона /// diff --git a/ProjectElectricLocomotive/ProjectElectricLocomotive/CollectionGenericObjects/CollectionInfo.cs b/ProjectElectricLocomotive/ProjectElectricLocomotive/CollectionGenericObjects/CollectionInfo.cs new file mode 100644 index 0000000..e1fec2b --- /dev/null +++ b/ProjectElectricLocomotive/ProjectElectricLocomotive/CollectionGenericObjects/CollectionInfo.cs @@ -0,0 +1,79 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectElectricLocomotive.CollectionGenericObjects; + +/// +/// Класс, хранящий информацию по коллекции +/// +public class CollectionInfo : IEquatable +{ + /// + /// Название + /// + public string Name { get; private set; } + + /// + /// Тип + /// + public CollectionType CollectionType { get; private set; } + + /// + /// Описание + /// + public string Description { get; private set; } + + /// + /// Разделитель для записи информации в файл + /// + private static readonly string _separator = "-"; + + /// + /// Конструктор + /// + /// Название + /// Тип + /// Описание + public CollectionInfo(string name, CollectionType collectionType, string description) + { + Name = name; + CollectionType = collectionType; + Description = description; + } + + /// + /// Создание объекта из строки + /// + /// Строка + /// Оьъект или null + public static CollectionInfo? GetCollectionInfo(string data) + { + string[] strs = data.Split(_separator, StringSplitOptions.RemoveEmptyEntries); + if (strs.Length < 1 || strs.Length > 3) return null; + else 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(); + } +} diff --git a/ProjectElectricLocomotive/ProjectElectricLocomotive/CollectionGenericObjects/ICollectionGenericObjects.cs b/ProjectElectricLocomotive/ProjectElectricLocomotive/CollectionGenericObjects/ICollectionGenericObjects.cs index 9eb3578..889aa54 100644 --- a/ProjectElectricLocomotive/ProjectElectricLocomotive/CollectionGenericObjects/ICollectionGenericObjects.cs +++ b/ProjectElectricLocomotive/ProjectElectricLocomotive/CollectionGenericObjects/ICollectionGenericObjects.cs @@ -1,4 +1,5 @@ -using System; +using ProjectElectricLocomotive.Drawnings; +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -11,7 +12,7 @@ namespace ProjectElectricLocomotive.CollectionGenericObjects; /// /// Параметр: ограничение - ссылочный тип public interface ICollectionGenericObjects - where T : class + where T : DrawningLocomotive { /// /// Количество объектов в коллекции @@ -28,13 +29,13 @@ public interface ICollectionGenericObjects /// /// Добавляемый объект /// true - вставка прошла удачно, false - вставка не удалась - int Insert(T obj); + int Insert(T obj, IEqualityComparer? comparer = null); /// /// Добавление объекта в коллекцию на конкретную позицию /// /// Добавляемый объект /// Позиция /// true - вставка прошла удачно, false - вставка не удалась - int Insert(T obj, int position); + int Insert(T obj, int position, IEqualityComparer? comparer = null); /// /// Удаление объекта из коллекции с конкретной позиции /// @@ -58,5 +59,10 @@ public interface ICollectionGenericObjects /// /// IEnumerable GetItems(); + /// + /// Сортировка коллекции + /// + /// + void CollectionSort(IComparer comparer); } \ No newline at end of file diff --git a/ProjectElectricLocomotive/ProjectElectricLocomotive/CollectionGenericObjects/ListGenericObjects.cs b/ProjectElectricLocomotive/ProjectElectricLocomotive/CollectionGenericObjects/ListGenericObjects.cs index 0af16a8..119eb89 100644 --- a/ProjectElectricLocomotive/ProjectElectricLocomotive/CollectionGenericObjects/ListGenericObjects.cs +++ b/ProjectElectricLocomotive/ProjectElectricLocomotive/CollectionGenericObjects/ListGenericObjects.cs @@ -1,4 +1,5 @@ -using ProjectElectricLocomotive.Exceptions; +using ProjectElectricLocomotive.Drawnings; +using ProjectElectricLocomotive.Exceptions; using System; using System.Collections.Generic; using System.Linq; @@ -8,7 +9,7 @@ using System.Threading.Tasks; namespace ProjectElectricLocomotive.CollectionGenericObjects; public class ListGenericObjects : ICollectionGenericObjects - where T : class + where T : DrawningLocomotive { /// /// Список объектов, которые храним @@ -60,7 +61,7 @@ public class ListGenericObjects : ICollectionGenericObjects } } - public int Insert(T obj) + public int Insert(T obj, IEqualityComparer? comparer = null) { if (Count == _maxCount) throw new CollectionOwerflowException(Count); @@ -68,12 +69,14 @@ public class ListGenericObjects : ICollectionGenericObjects return Count; } - public int Insert(T obj, int position) + public int Insert(T obj, int position, IEqualityComparer? comparer = null) { // проверка, что не превышено максимальное количество элементов // проверка позиции // вставка по позиции + if (_collection.Contains(obj, comparer)) throw new AlreadyExistingObject(obj.GetDataForSave()); + if (position > MaxCount) throw new CollectionOwerflowException(position); if (obj == null) throw new ArgumentNullException(nameof(obj)); diff --git a/ProjectElectricLocomotive/ProjectElectricLocomotive/CollectionGenericObjects/MassiveGenericObjects.cs b/ProjectElectricLocomotive/ProjectElectricLocomotive/CollectionGenericObjects/MassiveGenericObjects.cs index c09300d..d1c7dc6 100644 --- a/ProjectElectricLocomotive/ProjectElectricLocomotive/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/ProjectElectricLocomotive/ProjectElectricLocomotive/CollectionGenericObjects/MassiveGenericObjects.cs @@ -1,4 +1,5 @@ -using ProjectElectricLocomotive.Exceptions; +using ProjectElectricLocomotive.Drawnings; +using ProjectElectricLocomotive.Exceptions; using System; using System.Collections.Generic; using System.Linq; @@ -12,7 +13,7 @@ namespace ProjectElectricLocomotive.CollectionGenericObjects; /// /// Параметр: ограничение - ссылочный тип public class MassiveGenericObjects : ICollectionGenericObjects - where T : class + where T : DrawningLocomotive { /// /// Массив объектов, которые храним @@ -66,7 +67,7 @@ public class MassiveGenericObjects : ICollectionGenericObjects throw new PositionOutOfCollectionException(position); } } - public int Insert(T obj) + public int Insert(T obj, IEqualityComparer? comparer = null) { // вставка в свободное место набора for (int i = 0; i < Count; ++i) @@ -81,17 +82,14 @@ public class MassiveGenericObjects : ICollectionGenericObjects } - public int Insert(T obj, int position) + public int Insert(T obj, int position, IEqualityComparer? comparer = null) { // проверка позиции // проверка, что элемент массива по этой позиции пустой, если нет, то // ищется свободное место после этой позиции и идет вставка туда, если нет после, ищем до // вставка - if (position >= Count || position < 0) - { - return -1; - } + if (_collection.Contains(obj, comparer)) throw new AlreadyExistingObject(obj.GetDataForSave()); if (_collection[position] == null) { @@ -146,4 +144,14 @@ public class MassiveGenericObjects : ICollectionGenericObjects yield return _collection[i]; } } + + public void CollectionSort(IComparer comparer) + { + if (_collection?.Length > 0) + { + Array.Sort(_collection, comparer); + Array.Reverse(_collection); + } + } + } diff --git a/ProjectElectricLocomotive/ProjectElectricLocomotive/CollectionGenericObjects/StorageCollection.cs b/ProjectElectricLocomotive/ProjectElectricLocomotive/CollectionGenericObjects/StorageCollection.cs index b9d1c06..50b0d19 100644 --- a/ProjectElectricLocomotive/ProjectElectricLocomotive/CollectionGenericObjects/StorageCollection.cs +++ b/ProjectElectricLocomotive/ProjectElectricLocomotive/CollectionGenericObjects/StorageCollection.cs @@ -18,12 +18,12 @@ public class StorageCollection /// /// Словарь с коллекциями /// - readonly Dictionary> _storages; + readonly Dictionary> _storages; /// /// Возвращение списка названий коллекций /// - public List Keys => _storages.Keys.ToList(); + public List Keys => _storages.Keys.ToList(); /// /// Ключевое слово, с которого должен начинаться файл @@ -45,7 +45,7 @@ public class StorageCollection /// public StorageCollection() { - _storages = new Dictionary>(); + _storages = new Dictionary>(); } /// @@ -57,14 +57,15 @@ public class StorageCollection { // проверка что name не пустой и нет в словаре записи с таким ключом // логика добавления - if (string.IsNullOrEmpty(name) || _storages.ContainsKey(name) || collectionType == CollectionType.None) return; + CollectionInfo collectionInfo = new(name, collectionType, string.Empty); + if (string.IsNullOrEmpty(collectionInfo.Name) || _storages.ContainsKey(collectionInfo)) return; if (collectionType == CollectionType.Massive) { - _storages[name] = new MassiveGenericObjects(); + _storages[collectionInfo] = new MassiveGenericObjects(); } else if (collectionType == CollectionType.List) { - _storages[name] = new ListGenericObjects(); + _storages[collectionInfo] = new ListGenericObjects(); } } @@ -75,10 +76,9 @@ public class StorageCollection /// Имя коллекции public void DelCollection(string name) { - if (_storages.ContainsKey(name)) - { - _storages.Remove(name); - } + var obj = new CollectionInfo(name, CollectionType.None, string.Empty); + if (!_storages.ContainsKey(obj)) return; + _storages.Remove(obj); } public ICollectionGenericObjects? this[int index] @@ -113,9 +113,9 @@ public class StorageCollection using (StreamWriter writer = new StreamWriter(filename)) { writer.WriteLine(_collectionKey); - foreach (KeyValuePair> value in _storages) + foreach (KeyValuePair> value in _storages) { - writer.Write($"{value.Key}{_separatorForKeyValue}{value.Value.GetCollectionType}{_separatorForKeyValue}{value.Value.MaxCount}{_separatorForKeyValue}"); + writer.Write($"{value.Key}{_separatorForKeyValue}{value.Value.MaxCount}{_separatorForKeyValue}"); writer.Write(_separatorItems); foreach (T? item in value.Value.GetItems()) @@ -158,21 +158,22 @@ public class StorageCollection { string[] record = line.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); - if (record.Length != 4) + if (record.Length != 3) { line = reader.ReadLine(); continue; } - CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]); + CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(record[0]) ?? + throw new Exception("Не удалось определить информацию коллекции: " + record[0]); - ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType); + ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionInfo.CollectionType); if (collection == null) throw new NullCollectionExpection("Не удалось создать коллекцию"); ; - 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) { @@ -188,7 +189,7 @@ public class StorageCollection } } } - _storages.Add(record[0], collection); + _storages.Add(collectionInfo, collection); line = reader.ReadLine(); } diff --git a/ProjectElectricLocomotive/ProjectElectricLocomotive/Drawnings/DrawningLocomotiveCompareByColor.cs b/ProjectElectricLocomotive/ProjectElectricLocomotive/Drawnings/DrawningLocomotiveCompareByColor.cs new file mode 100644 index 0000000..e62cbd0 --- /dev/null +++ b/ProjectElectricLocomotive/ProjectElectricLocomotive/Drawnings/DrawningLocomotiveCompareByColor.cs @@ -0,0 +1,45 @@ +using ProjectElectricLocomotive.Entities; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectElectricLocomotive.Drawnings; + +/// +/// Сравнение по цвету, скорости, весу +/// +public class DrawningLocomotiveCompareByColor : IComparer +{ + public int Compare(DrawningLocomotive? x, DrawningLocomotive? y) + { + if (x == null && y == null) return 0; + if (x == null || x.EntityLocomotive == null) return -1; + if (y == null || y.EntityLocomotive == null) return 1; + if (x.GetType().Name != y.GetType().Name) return -1; + + var colorCompare = x.EntityLocomotive.BodyColor.ToArgb().CompareTo(y.EntityLocomotive.BodyColor.ToArgb()); + if (colorCompare != 0) + { + return colorCompare; + } + + if (x is DrawningElectricLocomotive && y is DrawningElectricLocomotive) + { + colorCompare = ((EntityElectricLocomotive)x.EntityLocomotive).AdditionalColor.ToArgb().CompareTo(((EntityElectricLocomotive)y.EntityLocomotive).AdditionalColor.ToArgb()); + if (colorCompare != 0) + { + return colorCompare; + } + } + + var speedCompare = x.EntityLocomotive.Speed.CompareTo(y.EntityLocomotive.Speed); + if (speedCompare != 0) + { + return speedCompare; + } + + return x.EntityLocomotive.Weight.CompareTo(y.EntityLocomotive.Weight); + } +} diff --git a/ProjectElectricLocomotive/ProjectElectricLocomotive/Drawnings/DrawningLocomotiveCompareByType.cs b/ProjectElectricLocomotive/ProjectElectricLocomotive/Drawnings/DrawningLocomotiveCompareByType.cs new file mode 100644 index 0000000..031c4e8 --- /dev/null +++ b/ProjectElectricLocomotive/ProjectElectricLocomotive/Drawnings/DrawningLocomotiveCompareByType.cs @@ -0,0 +1,31 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectElectricLocomotive.Drawnings; + +/// +/// Сравнение по типу, скорости, весу +/// +public class DrawningLocomotiveCompareByType : IComparer +{ + public int Compare(DrawningLocomotive? x, DrawningLocomotive? y) + { + if (x == null && y == null) return 0; + if (x == null || x.EntityLocomotive == null) return -1; + if (y == null || y.EntityLocomotive == null) return 1; + if (x.GetType().Name != y.GetType().Name) + { + return x.GetType().Name.CompareTo(y.GetType().Name); + } + var speedCompare = x.EntityLocomotive.Speed.CompareTo(y.EntityLocomotive.Speed); + if (speedCompare != 0) + { + return speedCompare; + } + return x.EntityLocomotive.Weight.CompareTo(y.EntityLocomotive.Weight); + + } +} diff --git a/ProjectElectricLocomotive/ProjectElectricLocomotive/Drawnings/DrawningLocomotiveEqutables.cs b/ProjectElectricLocomotive/ProjectElectricLocomotive/Drawnings/DrawningLocomotiveEqutables.cs new file mode 100644 index 0000000..ec5e662 --- /dev/null +++ b/ProjectElectricLocomotive/ProjectElectricLocomotive/Drawnings/DrawningLocomotiveEqutables.cs @@ -0,0 +1,34 @@ +using ProjectElectricLocomotive.Entities; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectElectricLocomotive.Drawnings; + +public class DrawningLocomotiveEqutables : IEqualityComparer +{ + public bool Equals(DrawningLocomotive? x, DrawningLocomotive? y) + { + if (x == null || x.EntityLocomotive == null) return false; + if (y == null || y.EntityLocomotive == null) return false; + if (x.GetType().Name != y.GetType().Name) return false; + if (x.EntityLocomotive.Speed != y.EntityLocomotive.Speed) return false; + if (x.EntityLocomotive.Weight != y.EntityLocomotive.Weight) return false; + if (x.EntityLocomotive.BodyColor != y.EntityLocomotive.BodyColor) return false; + if (x is DrawningElectricLocomotive && y is DrawningElectricLocomotive) + { + if (((EntityElectricLocomotive)x.EntityLocomotive).AdditionalColor != ((EntityElectricLocomotive)y.EntityLocomotive).AdditionalColor) return false; + if (((EntityElectricLocomotive)x.EntityLocomotive).ElectricHorns != ((EntityElectricLocomotive)y.EntityLocomotive).ElectricHorns) return false; + if (((EntityElectricLocomotive)x.EntityLocomotive).BatteryPlacement != ((EntityElectricLocomotive)y.EntityLocomotive).BatteryPlacement) return false; + } + return true; + } + + public int GetHashCode([DisallowNull] DrawningLocomotive obj) + { + return obj.GetHashCode(); + } +} diff --git a/ProjectElectricLocomotive/ProjectElectricLocomotive/Exceptions/AlreadyExistingObject.cs b/ProjectElectricLocomotive/ProjectElectricLocomotive/Exceptions/AlreadyExistingObject.cs new file mode 100644 index 0000000..8229aa3 --- /dev/null +++ b/ProjectElectricLocomotive/ProjectElectricLocomotive/Exceptions/AlreadyExistingObject.cs @@ -0,0 +1,23 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectElectricLocomotive.Exceptions; + +/// +/// Класс, описывающий переполнение коллекции +/// +[Serializable] +internal class AlreadyExistingObject : ApplicationException +{ + public AlreadyExistingObject(string objName) : base("Данный объект уже существует " + objName) { } + + public AlreadyExistingObject() : base() { } + + public AlreadyExistingObject(string message, Exception exception) : base(message, exception) { } + + public AlreadyExistingObject(SerializationInfo info, StreamingContext context) : base(info, context) { } +}