88 lines
2.5 KiB
C#
88 lines
2.5 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace Lab.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?>(_maxCount);
|
|
}
|
|
|
|
public bool Insert(T car, IEqualityComparer<T?>? equal = null)
|
|
{
|
|
return Insert(car, 0, equal);
|
|
}
|
|
public bool Insert(T car, int position, IEqualityComparer<T?>? equal = null)
|
|
{
|
|
if (position < 0 || position >= _maxCount)
|
|
throw new CarNotFoundException(position);
|
|
if (Count >= _maxCount)
|
|
throw new StorageOverflowException(position);
|
|
if (equal != null)
|
|
{
|
|
foreach (var i in _places)
|
|
{
|
|
if (equal.Equals(i, car))
|
|
throw new ArgumentException($"Объект {car} уже существует");
|
|
}
|
|
}
|
|
_places.Insert(0, car);
|
|
return true;
|
|
}
|
|
|
|
public bool Remove(int position)
|
|
{
|
|
if (position < 0 || position > _maxCount || position >= Count)
|
|
throw new CarNotFoundException(position);
|
|
_places.RemoveAt(position);
|
|
return true;
|
|
}
|
|
public T? this[int position]
|
|
{
|
|
get
|
|
{
|
|
if (position < 0 || position > _maxCount)
|
|
return null;
|
|
if (_places.Count <= position)
|
|
return null;
|
|
return _places[position];
|
|
}
|
|
set
|
|
{
|
|
if (position < 0 || position > _maxCount)
|
|
return;
|
|
if (_places.Count <= position)
|
|
return;
|
|
_places[position] = value;
|
|
}
|
|
}
|
|
|
|
|
|
public IEnumerable<T?> GetCars(int? maxCars = null)
|
|
{
|
|
for (int i = 0; i < _places.Count; ++i)
|
|
{
|
|
yield return _places[i];
|
|
if (maxCars.HasValue && i == maxCars.Value)
|
|
{
|
|
yield break;
|
|
}
|
|
}
|
|
}
|
|
|
|
public void SortSet(IComparer<T?> comparer) => _places.Sort(comparer);
|
|
|
|
}
|
|
}
|