PIbd22_NikiforovaMV_Contain.../ContainerShip/SetGeneric.cs

87 lines
2.4 KiB
C#
Raw Normal View History

2023-12-16 11:10:10 +04:00
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
2023-12-29 22:18:15 +04:00
using ContainerShip.Exceptions;
2023-12-16 11:10:10 +04:00
namespace ContainerShip.Generic
{
internal class SetGeneric<T>
where T : class
{
2023-12-16 11:14:14 +04:00
private readonly List<T?> _places;
public int Count => _places.Count;
private readonly int _maxCount;
2023-12-16 11:10:10 +04:00
public SetGeneric(int count)
{
2023-12-16 11:14:14 +04:00
_maxCount = count;
_places = new List<T?>(count);
2023-12-16 11:10:10 +04:00
}
2023-12-29 22:22:08 +04:00
public void SortSet(IComparer<T?> comparer) => _places.Sort(comparer);
public int Insert(T ship, IEqualityComparer<T?>? equal = null)
2023-12-16 11:10:10 +04:00
{
2023-12-29 22:22:08 +04:00
return Insert(ship, 0, equal);
2023-12-16 11:10:10 +04:00
}
2023-12-29 22:22:08 +04:00
public int Insert(T ship, int position, IEqualityComparer<T?>? equal = null)
2023-12-16 11:10:10 +04:00
{
2023-12-29 22:18:15 +04:00
if (Count >= _maxCount)
{
throw new StorageOverflowException(_maxCount);
}
if (position < 0 || position >= _maxCount)
2023-12-16 11:10:10 +04:00
{
2023-12-29 22:18:15 +04:00
throw new IndexOutOfRangeException("Индекс вне границ коллекции");
2023-12-16 11:10:10 +04:00
}
2023-12-29 22:22:08 +04:00
if (equal != null && _places.Contains(ship, equal))
{
throw new ArgumentException("Данный объект уже есть в коллекции");
}
2023-12-16 11:14:14 +04:00
_places.Insert(position, ship);
2023-12-29 22:18:15 +04:00
return 0;
2023-12-16 11:10:10 +04:00
}
public bool Remove(int position)
{
2023-12-16 11:14:14 +04:00
if (position < 0 || position >= Count)
2023-12-16 11:10:10 +04:00
{
2023-12-29 22:18:15 +04:00
throw new ShipNotFoundException(position);
2023-12-16 11:10:10 +04:00
}
2023-12-16 11:14:14 +04:00
_places.RemoveAt(position);
2023-12-16 11:10:10 +04:00
return true;
}
2023-12-16 11:14:14 +04:00
public T? this[int position]
{
get
{
if (position < 0 || position >= Count)
{
return null;
}
return _places[position];
}
set
{
2023-12-29 22:22:08 +04:00
if (position < 0 || Count >= _maxCount)
2023-12-16 11:14:14 +04:00
{
return;
}
2023-12-29 22:22:08 +04:00
2023-12-16 11:14:14 +04:00
_places.Insert(position, value);
}
}
public IEnumerable<T?> GetShip(int? maxShip = null)
2023-12-16 11:10:10 +04:00
{
2023-12-16 11:14:14 +04:00
for (int i = 0; i < _places.Count; ++i)
2023-12-16 11:10:10 +04:00
{
2023-12-16 11:14:14 +04:00
yield return _places[i];
if (maxShip.HasValue && i == maxShip.Value)
{
yield break;
}
2023-12-16 11:10:10 +04:00
}
}
2023-12-16 11:14:14 +04:00
2023-12-16 11:10:10 +04:00
}
}