87 lines
2.7 KiB
C#
87 lines
2.7 KiB
C#
using ProjectBulldozer.Exceptions;
|
|
namespace ProjectBulldozer.Generics
|
|
{
|
|
internal class SetGeneric<T> where T : class
|
|
{
|
|
private readonly List<T?> _places;
|
|
public int Count => _places.Count;
|
|
/// Максимальное количество объектов в списке
|
|
private readonly int _maxCount;
|
|
public SetGeneric(int count)
|
|
{
|
|
_maxCount = count;
|
|
_places = new List<T?>(count);
|
|
}
|
|
/// Добавление объекта в набор
|
|
public int Insert(T tractor, IEqualityComparer<T?>? equal = null)
|
|
{
|
|
if (_places.Count == _maxCount)
|
|
throw new StorageOverflowException(_maxCount);
|
|
Insert(tractor, 0, equal);
|
|
return 0;
|
|
}
|
|
public bool Insert(T tractor, int position, IEqualityComparer<T?>? equal = null)
|
|
{
|
|
if (position < 0 || position >= _maxCount)
|
|
{
|
|
throw new BulldozerNotFoundException(position);
|
|
}
|
|
if (Count >= _maxCount)
|
|
{
|
|
throw new StorageOverflowException(_maxCount);
|
|
}
|
|
if (equal != null)
|
|
{
|
|
foreach (var i in _places)
|
|
{
|
|
if (equal.Equals(i, tractor))
|
|
{
|
|
throw new ApplicationException($"Объект уже существует");
|
|
}
|
|
}
|
|
}
|
|
_places.Insert(position, tractor);
|
|
return true;
|
|
}
|
|
public bool Remove(int position)
|
|
{
|
|
if (position < 0 || position >= _maxCount)
|
|
{
|
|
return false;
|
|
}
|
|
if (_places[position] == null)
|
|
{
|
|
throw new BulldozerNotFoundException(position);
|
|
}
|
|
_places[position] = null;
|
|
return true;
|
|
}
|
|
public T? this[int position]
|
|
{
|
|
get
|
|
{
|
|
if (position < 0 || position >= Count) return null;
|
|
return _places[position];
|
|
}
|
|
set
|
|
{
|
|
if (position < 0 || position >= Count || Count == _maxCount) return;
|
|
_places.Insert(position, value);
|
|
}
|
|
}
|
|
public IEnumerable<T?> GetTractors(int? maxTracts = null)
|
|
{
|
|
for (int i = 0; i < _places.Count; ++i)
|
|
{
|
|
yield return _places[i];
|
|
if (maxTracts.HasValue && i == maxTracts.Value)
|
|
{
|
|
yield break;
|
|
}
|
|
}
|
|
}
|
|
|
|
public void SortSet(IComparer<T?> comparer) => _places.Sort(comparer);
|
|
}
|
|
}
|