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 class CollectionTally
{
public class CollectionTallyResult
{
public List<object> ExtraItems { get; set; }
public List<object> MissingItems { get; set; }
public CollectionTallyResult()
{
ExtraItems = new List<object>();
MissingItems = new List<object>();
}
}
private readonly NUnitEqualityComparer comparer;
private List<object> _missingItems = new List<object>();
private List<object> _extraItems = new List<object>();
public CollectionTallyResult Result => new CollectionTallyResult {
MissingItems = new List<object>(_missingItems),
ExtraItems = 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);
}
}
}
}