Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
[TestFixture]
public class SafeListTests
{
[Test]
public void TestRemoveWithDiscards()
{
// Fill with 1..10
var undertest = SafeList<int>.Empty.AddRange(Enumerable.Range(1, 10));
Assert.AreEqual(10, undertest.Count);
// Remove number 5
List<int> discards;
var without5 = undertest.RemoveAllAndGetDiscards(i => i == 5, out discards);
// 5 should be discarded
Assert.AreEqual(5, discards.Single());
Assert.AreEqual(9, without5.Count);
Assert.That(!without5.Contains(5));
}
public class SafeList<T> : IEnumerable<T>
{
private List<T> _inner = new List<T>();
public static readonly SafeList<T> Empty = new SafeList<T>();
private SafeList()
{
}
public SafeList<T> AddRange(IEnumerable<T> items)
{
var inner = new List<T>(_inner);
inner.AddRange(items);
return new SafeList<T>
{
_inner = inner
};
}
public SafeList<T> Add(T item)
{
return new SafeList<T>
{
_inner = new List<T>(_inner) { item }
};
}
public int Count
{
get { return _inner.Count; }
}
public T this[int i]
{
get { return _inner[i]; }
}
public SafeList<T> RemoveAll(Func<T, bool> filter)
{
return new SafeList<T>
{
_inner = new List<T>(_inner.Where(x => filter(x) == false))
};
}
public T Find(Predicate<T> predicate)
{
return _inner.Find(predicate);
}
public SafeList<T> RemoveAllAndGetDiscards(Predicate<T> filter, out List<T> discards)
{
var list = new List<T>();
discards = list;
return new SafeList<T>
{
_inner = new List<T>(_inner.Where(x =>
{
if (filter(x) == false)
{
list.Add(x);
return false;
}
return true;
}))
};
}
public IEnumerator<T> GetEnumerator()
{
return _inner.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return _inner.GetEnumerator();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.