PIbd-23_Vrazhkin_S_A_Electr.../lab1/Generics/SetGeneric.cs

76 lines
2.1 KiB
C#
Raw Normal View History

2023-11-28 13:43:14 +04:00
using ElectricLocomotive.Exceptions;
namespace ElectricLocomotive;
2023-10-17 13:49:31 +04:00
2023-10-31 11:39:52 +04:00
public class SetGeneric <T> where T : class
2023-10-17 13:49:31 +04:00
{
2023-10-31 13:25:13 +04:00
private readonly List<T?> _places;
2023-10-17 13:49:31 +04:00
2023-10-31 13:25:13 +04:00
public int Count => _places.Count;
private readonly int _maxCount;
2023-10-17 13:49:31 +04:00
public SetGeneric(int count)
{
2023-10-31 13:25:13 +04:00
_maxCount = count;
_places = new List<T>(count);
2023-10-17 13:49:31 +04:00
}
2023-12-12 13:58:32 +04:00
public void SortSet(IComparer<T?> comparer) => _places.Sort(comparer);
public bool Insert(T electricLocomotiv, IEqualityComparer<T>? equal = null)
2023-10-17 13:49:31 +04:00
{
2023-10-31 13:25:13 +04:00
if (_places.Count == _maxCount)
2023-11-28 13:43:14 +04:00
throw new StorageOverflowException(_maxCount);
2023-12-12 13:58:32 +04:00
Insert(electricLocomotiv, 0, equal);
2023-10-31 13:25:13 +04:00
return true;
2023-10-17 13:49:31 +04:00
}
2023-12-12 13:58:32 +04:00
public bool Insert(T electricLocomotiv, int position, IEqualityComparer<T>? equal = null)
2023-10-17 13:49:31 +04:00
{
2023-11-28 13:43:14 +04:00
if (_places.Count == _maxCount)
throw new StorageOverflowException(_maxCount);
if (!(position >= 0 && position <= Count))
2023-10-31 13:25:13 +04:00
return false;
2023-12-12 13:58:32 +04:00
if(equal != null)
{
if (_places.Contains(electricLocomotiv, equal))
throw new ArgumentException(nameof(electricLocomotiv));
}
2023-10-31 13:25:13 +04:00
_places.Insert(position, electricLocomotiv);
return true;
2023-10-17 13:49:31 +04:00
}
public bool Remove(int position)
{
2023-10-31 13:25:13 +04:00
if (!(position >= 0 && position < Count))
2023-11-28 13:43:14 +04:00
throw new LocoNotFoundException(position);
2023-10-31 13:25:13 +04:00
_places.RemoveAt(position);
2023-10-17 13:49:31 +04:00
return true;
}
2023-10-31 13:25:13 +04:00
public T? this[int position]
2023-10-17 13:49:31 +04:00
{
2023-10-31 13:25:13 +04:00
get {
if (!(position >= 0 && position < Count))
return null;
return _places[position];
}
set {
if (!(position >= 0 && position < Count && _places.Count < _maxCount))
return;
_places.Insert(position, value);
return;
}
}
public IEnumerable<T?> GetElectricLocos(int? maxElectricLocos = null)
{
for (int i = 0; i < _places.Count; ++i)
{
yield return _places[i];
if (maxElectricLocos.HasValue && i == maxElectricLocos.Value)
{
yield break;
}
}
2023-10-17 13:49:31 +04:00
}
}