I'm trying to write an extension (method chaining) for playing around a bit.
What I made work is an extension to add an item to the list (what is pretty easy):
IEnumerable<int> myList = originalList.Add(12);
What I now want to do is:
IEnumerable<int> myList = originalList.Add(12).If((list, @new) => !list.Contains(@new));
What it should do:
If the originalList
doesn't already contain @new
(12), then it may not add it to the list.
If the If
-sequence is not added, the element gets added.
So this is my code:
public static class EnumerableExtension
{
public static IAddEnumerable<T> Add<T>(this IEnumerable<T> @this, T element)
=> new AddEnumerable<T>(@this, element);
}
public interface IAddEnumerable<T> : IEnumerable<T>
{
IEnumerable<T> If(Func<IEnumerable<T>, T, bool> expression);
}
internal class AddEnumerable<T> : IAddEnumerable<T>
{
private IEnumerable<T> _sequence;
private readonly T _elementToAdd;
private bool _added;
public AddEnumerable(IEnumerable<T> sequence, T elementToAdd)
{
_sequence = sequence;
_elementToAdd = elementToAdd;
}
public IEnumerable<T> If(Func<IEnumerable<T>, T, bool> expression)
{
_added = true;
if (expression(_sequence,_elementToAdd))
_sequence = _sequence.AddItem(_elementToAdd);
return this;
}
public IEnumerator<T> GetEnumerator()
{
if (_added)
return _sequence.GetEnumerator();
_sequence = _sequence.AddItem(_elementToAdd);
_added = true;
return _sequence.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
if (_added)
return _sequence.GetEnumerator();
_sequence = _sequence.AddItem(_elementToAdd);
_added = true;
return _sequence.GetEnumerator();
}
}
It works, but I wanted to ask, if there are any problems that could come up with, or if there is something I could do better.
AddEnumerable
constructors feels really strange. What's the sole purpose of the_elementToAdd
private field? \$\endgroup\$If
is true, or there is noIf
. \$\endgroup\$If
builder method. That's why the complexity goes intoGetEnumerator
methods. You have code duplication because of this. \$\endgroup\$