PIbd_23_Kislitsa_E.D_AirFig.../AirFighter/SetGeneric.cs

88 lines
2.5 KiB
C#
Raw Permalink Normal View History

2023-10-15 17:11:27 +04:00
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
2023-12-08 22:44:38 +04:00
using ProjectAirFighter.Exceptions;
using System.Windows.Forms;
2023-10-15 17:11:27 +04:00
namespace ProjectAirFighter.Generics
{
internal class SetGeneric<T>
where T : class
{
2023-10-27 00:17:04 +04:00
private readonly List<T?> _places;
2023-10-15 17:11:27 +04:00
2023-10-27 00:17:04 +04:00
public int Count => _places.Count;
2023-10-15 17:11:27 +04:00
2023-10-27 00:17:04 +04:00
private readonly int _maxCount;
2023-10-15 17:11:27 +04:00
public SetGeneric(int count)
{
2023-10-27 00:17:04 +04:00
_maxCount = count;
_places = new List<T?>(count);
2023-10-15 17:11:27 +04:00
}
public void SortSet(IComparer<T?> comparer) => _places.Sort(comparer);
public bool Insert(T airplane, IEqualityComparer<T>? equal = null)
2023-10-15 17:11:27 +04:00
{
2023-10-27 00:17:04 +04:00
if (_places.Count == _maxCount)
2023-12-08 22:44:38 +04:00
throw new StorageOverflowException(_maxCount);
Insert(airplane, 0, equal);
2023-10-27 00:17:04 +04:00
return true;
2023-10-15 17:11:27 +04:00
}
public bool Insert(T airplane, int position, IEqualityComparer<T>? equal = null)
2023-10-15 17:11:27 +04:00
{
2023-12-08 22:44:38 +04:00
if (_places.Count == _maxCount)
throw new StorageOverflowException(_maxCount);
if (!(position >= 0 && position <= Count))
2023-10-27 00:17:04 +04:00
return false;
if (equal != null)
{
if (_places.Contains(airplane, equal))
throw new ArgumentException(nameof(airplane));
}
2023-10-27 00:17:04 +04:00
_places.Insert(position, airplane);
return true;
2023-10-15 17:11:27 +04:00
}
public bool Remove(int position)
{
2023-10-27 00:17:04 +04:00
if (!(position >= 0 && position < Count))
2023-12-08 22:44:38 +04:00
throw new AirplaneNotFoundException(position);
2023-10-27 00:17:04 +04:00
_places.RemoveAt(position);
2023-10-15 17:11:27 +04:00
return true;
}
2023-10-27 00:17:04 +04:00
public T? this[int position]
{
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;
}
}
2023-10-15 17:11:27 +04:00
2023-10-27 00:17:04 +04:00
public IEnumerable<T?> GetAirplanes(int? maxAirplanes = null)
2023-10-15 17:11:27 +04:00
{
2023-10-27 00:17:04 +04:00
for (int i = 0; i < _places.Count; ++i)
{
yield return _places[i];
if (maxAirplanes.HasValue && i == maxAirplanes.Value)
{
yield break;
}
}
2023-10-15 17:11:27 +04:00
}
2023-10-27 00:17:04 +04:00
2023-10-15 17:11:27 +04:00
}
}