PIbd-14_Pruidze_I.K_Simple_.../ProjectCruiser/CollectionGenericObj/ArrayGenObj.cs

105 lines
2.2 KiB
C#
Raw Normal View History

2024-06-15 13:28:42 +04:00

namespace ProjectCruiser.CollectionGenericObj;
public class ArrayGenObj<T> : ICollectionGenObj<T>
where T : class
{
// Массив объектов, которые храним
private T?[] _collection;
public int Count => _collection.Length;
2024-06-15 13:28:42 +04:00
public int MaxCount
{
2024-06-15 13:28:42 +04:00
get { return _collection.Length; }
2024-06-15 09:05:36 +04:00
set
{
if (value > 0)
{
if (_collection.Length > 0) Array.Resize(ref _collection, value);
else _collection = new T?[value];
}
}
}
2024-06-15 13:28:42 +04:00
public CollectionType GetCollectionType => CollectionType.Array;
public ArrayGenObj()
{
_collection = Array.Empty<T?>();
}
// methods :
public T? GetItem(int index)
{
if (index > Count || index < 0)
{
return null;
}
return _collection[index];
}
public int Insert(T? item)
{
// any empty place
for (int i = 0; i < Count; i++)
{
if (_collection[i] == null)
{
_collection[i] = item;
return i;
}
}
return -1;
}
public int Insert(T? item, int index)
{
if (_collection[index] == null)
{
_collection[index] = item;
return index;
}
else
{
int min_diff = 100, min_index = 100;
for (int i = 0; i < Count; i++)
{
2024-06-15 09:05:36 +04:00
if (_collection[i] == null
&& min_diff > Math.Abs(index - i))
{
min_diff = Math.Abs(index - i);
min_index = i;
}
}
_collection[min_index] = item;
return min_index;
}
return -1;
}
public T? Remove(int index)
{
T? item;
if (index < Count && index >= 0)
{
item = _collection[index];
_collection[index] = null;
return item;
}
return null;
}
2024-06-15 13:28:42 +04:00
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < _collection.Length; ++i)
{
yield return _collection[i];
}
}
}