PIbd-22_Fedorenko_G.Y._Hydr.../Hydroplane/SetGeneric.cs

99 lines
2.9 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Hydroplane.Exceptions;
namespace Hydroplane.Generics
{
internal class SetGeneric<T> where T : class
{
private readonly List<T?> _places;
public int Count => _places.Count;
private readonly int _maxCount;
public void SortSet(IComparer<T?> comparer) => _places.Sort(comparer);
public SetGeneric(int count)
{
_maxCount = count;
_places = new List<T?>(_maxCount);
}
public bool Insert(T plane, IEqualityComparer<T?>? equal = null)
{
if (equal != null)
{
foreach (var secondPlane in _places)
{
if (equal.Equals(plane, secondPlane))
{
throw new Exception("Такой объект уже есть в коллекции");
}
}
}
return Insert(plane, 0);
}
public bool Insert(T plane, int position, IEqualityComparer<T?>? equal = null)
{
if (position < 0 || position >= _maxCount)
throw new StorageOverflowException("Impossible to insert");
if (Count >= _maxCount)
throw new StorageOverflowException(_maxCount);
if (equal != null)
{
foreach (var secondPlane in _places)
{
if (equal.Equals(plane, secondPlane))
{
throw new ApplicationException("Такой объект уже есть в коллекции");
}
}
}
_places.Insert(position, plane);
return true;
}
public bool Remove(int position)
{
if (position >= Count || position < 0)
throw new PlaneNotFoundException("Invalid operation");
if (_places[position] == null)
throw new PlaneNotFoundException(position);
_places.RemoveAt(position);
return true;
}
public T? this[int position]
{
get
{
if (position < 0 || position > _maxCount)
return null;
return _places[position];
}
set
{
if (position < 0 || position > _maxCount)
return;
_places[position] = value;
}
}
public IEnumerable<T?> GetPlanes(int? maxPlanes = null)
{
for (int i = 0; i < _places.Count; ++i)
{
yield return _places[i];
if (maxPlanes.HasValue && i == maxPlanes.Value)
{
yield break;
}
}
}
}
}