CollectionTally
CollectionTally counts (tallies) the number of occurrences
of each object in one or more enumerations.
using NUnit.Framework.Internal.Extensions;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.CompilerServices;
namespace NUnit.Framework.Constraints
{
[System.Runtime.CompilerServices.NullableContext(1)]
[System.Runtime.CompilerServices.Nullable(0)]
public sealed class CollectionTally
{
[System.Runtime.CompilerServices.Nullable(0)]
[DebuggerDisplay("Missing = {MissingItems.Count}, Extra = {ExtraItems.Count}")]
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 bool _isSortable;
private bool _sorted;
private readonly List<object> _missingItems = new List<object>();
private readonly List<object> _extraItems = new List<object>();
public CollectionTallyResult Result {
get {
List<object> list = new List<object>(_missingItems.Count);
foreach (object missingItem in _missingItems) {
list.Add(missingItem);
}
List<object> list2 = new List<object>(_extraItems.Count);
if (_sorted) {
for (int num = _extraItems.Count - 1; num >= 0; num--) {
list2.Add(_extraItems[num]);
}
} else
list2.AddRange(_extraItems);
return new CollectionTallyResult(list, list2);
}
}
public CollectionTally(NUnitEqualityComparer comparer, IEnumerable c)
{
_comparer = comparer;
_missingItems = ToList(c);
if (c.IsSortable()) {
_missingItems.Sort();
_isSortable = true;
}
}
private bool ItemsEqual(object expected, object actual)
{
Tolerance tolerance = Tolerance.Default;
return _comparer.AreEqual(expected, actual, ref tolerance);
}
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)
{
if (_isSortable && c.IsSortable()) {
List<object> list = ToList(c);
list.Sort();
_sorted = true;
for (int num = list.Count - 1; num >= 0; num--) {
TryRemove(list[num]);
}
} else
<TryRemove>g__TryRemoveSlow|11_0(c);
}
private static List<object> ToList(IEnumerable items)
{
ICollection collection = items as ICollection;
List<object> list = (collection != null) ? new List<object>(collection.Count) : new List<object>();
foreach (object item in items) {
list.Add(item);
}
return list;
}
}
}