Occasionally I find I need to process a list by inserting a new item after each item, except the last one. Similar to how you might put a comma between each item of a list of strings.
I got fed up of coding the special case for the last (or first) item every time, so I captured the pattern in a Linq-style extension:
public static IEnumerable<T> Separate<T>(this IEnumerable<T> source,
Func<T> separator)
{
bool first = true;
foreach (T item in source)
{
if (first)
first = false;
else
yield return separator();
yield return item;
}
}
For example, this allows me to easily programatically fill a flow document with hyperlinks, but with a line-break between each one:
para.Inlines.AddRange(_recentFiles.Select(f => f.ToHyperlink())
.Separate(() => new LineBreak()));
Assuming this doesn't already exist in System.Linq.Enumerable (which is what I typically discover immediately after writing something like this), the question is, what is this Separate
operation on lists usually called in other functional frameworks or languages?