SortedSet<T>.Trim extension

This commit is contained in:
vis2k 2022-04-29 18:48:06 +08:00
parent 4d891fc5a1
commit 590c26d807
2 changed files with 37 additions and 0 deletions

View File

@ -53,5 +53,16 @@ public static bool TryDequeue<T>(this Queue<T> source, out T element)
return false; return false;
} }
#endif #endif
// helper function to trim a set to a max length
public static void Trim<T>(this SortedSet<T> set, int maxLength)
{
// make sure we don't deadlock for negative length
if (maxLength < 0) return;
// remove while count > max
while (set.Count > maxLength)
set.Remove(set.Max);
}
} }
} }

View File

@ -22,5 +22,31 @@ public void CopyToList()
source.CopyTo(destination); source.CopyTo(destination);
Assert.That(destination.SequenceEqual(source), Is.True); Assert.That(destination.SequenceEqual(source), Is.True);
} }
[Test]
public void SortedSet_Trim()
{
SortedSet<int> set = new SortedSet<int>{1, 2, 3, 4, 5};
// larger than count
set.Trim(6);
Assert.That(set.SequenceEqual(new []{1, 2, 3, 4, 5}));
// exactly count
set.Trim(5);
Assert.That(set.SequenceEqual(new []{1, 2, 3, 4, 5}));
// smaller than count
set.Trim(3);
Assert.That(set.SequenceEqual(new []{1, 2, 3}));
// negative should not deadlock
set.Trim(-1);
Assert.That(set.SequenceEqual(new []{1, 2, 3}));
// zero
set.Trim(0);
Assert.That(set.SequenceEqual(new int[0]));
}
} }
} }