Files
Recyclable.Collections/Recyclable.Collections/RecyclableSortedList.cs
T
mlemanczyk aba28028b1 Performance & standardization improvements.
Business logic fixes.
RecyclableQueue & RecyclableStack added - pending improvements.
2023-01-06 13:54:32 +01:00

79 lines
1.5 KiB
C#

namespace Recyclable.Collections
{
public class RecyclableSortedList<TKey, TValue> : RecyclableList<(TKey Key, TValue Value)>
where TKey : notnull
{
private static readonly IComparer<(TKey, TValue)> _comparer = new FrequencyTupleComparer<TKey, TValue>();
private uint _isUpdating;
private readonly SystemRandomNumberGenerator _randomNumberGenerator = new();
protected void ListUpdated()
{
QuickSort();
}
public RecyclableSortedList() : base()
{
}
public RecyclableSortedList(Dictionary<TKey, TValue> source, int blockSize = RecyclableDefaults.BlockSize)
: this(source.Select(x => (x.Key, x.Value)), blockSize)
{
}
public RecyclableSortedList(IEnumerable<(TKey Key, TValue Value)> source, int blockSize = RecyclableDefaults.BlockSize)
: base(source, blockSize)
{
QuickSort();
}
public RecyclableSortedList(int blockSize = RecyclableDefaults.BlockSize)
: base(blockSize)
{
}
public bool IsUpdating => _isUpdating > 0;
public void Add(TKey key, TValue value) => Add((key, value));
public void BeginUpdate() => _isUpdating++;
public void Clear()
{
BeginUpdate();
try
{
base.Clear();
}
finally
{
EndUpdate();
}
}
public void EndUpdate(bool raiseListUpdated = true)
{
if (_isUpdating > 0)
{
_isUpdating--;
if (raiseListUpdated && _isUpdating == 0)
{
ListUpdated();
}
}
}
public void QuickSort()
{
BeginUpdate();
try
{
this.QuickSort(_comparer, _randomNumberGenerator);
}
finally
{
EndUpdate(false);
}
}
}
}