CollectionTally
CollectionTally counts (tallies) the number of occurrences
of each object in one or more enumerations.
using System.Collections;
using System.Collections.Generic;
namespace NUnit.Framework.Constraints
{
public sealed class CollectionTally
{
public sealed class CollectionTallyResult
{
public List<object> ExtraItems { get; }
public List<object> MissingItems { get; }
public CollectionTallyResult(List<object> missingItems, List<object> extraItems)
{
MissingItems = missingItems;
ExtraItems = extraItems;
}
}
private readonly NUnitEqualityComparer comparer;
private readonly List<object> _missingItems = new List<object>();
private readonly List<object> _extraItems = new List<object>();
public CollectionTallyResult Result => new CollectionTallyResult(new List<object>(_missingItems), new List<object>(_extraItems));
public CollectionTally(NUnitEqualityComparer comparer, IEnumerable c)
{
this.comparer = comparer;
foreach (object item in c) {
_missingItems.Add(item);
}
}
private bool ItemsEqual(object expected, object actual)
{
Tolerance tolerance = Tolerance.Default;
return comparer.AreEqual(expected, actual, ref tolerance, true);
}
public void TryRemove(object o)
{
for (int num = _missingItems.Count - 1; num >= 0; num--) {
if (ItemsEqual(_missingItems[num], o)) {
_missingItems.RemoveAt(num);
return;
}
}
_extraItems.Add(o);
}
public void TryRemove(IEnumerable c)
{
foreach (object item in c) {
TryRemove(item);
}
}
}
}