An analog of String.Join(string, string[]) for IEnumerable<T>
The Linq equivalent of String.Join
is Aggregate
For instance:
IEnumerable<string> strings;
string joinedString = strings.Aggregate((total,next) => total + ", " + next);
If given an IE of TableRows, the code will be similar.
I wrote an extension method:
public static IEnumerable<T>
Join<T>(this IEnumerable<T> src, Func<T> separatorFactory)
{
var srcArr = src.ToArray();
for (int i = 0; i < srcArr.Length; i++)
{
yield return srcArr[i];
if(i<srcArr.Length-1)
{
yield return separatorFactory();
}
}
}
You can use it as follows:
tableRowList.Join(()=>new TableRow())
In .NET 3.5 you can use this extension method:
public static string Join<TItem>(this IEnumerable<TItem> enumerable, string separator)
{
return string.Join(separator, enumerable.Select(x => x.ToString()).ToArray());
}
or in .NET 4
public static string Join<TItem>(this IEnumerable<TItem> enumerable, string separator)
{
return string.Join(separator, enumerable);
}
BUT the question wanted a separator after each element including the last for which this (3.5 version) would work:-
public static string AddDelimiterAfter<TItem>(this IEnumerable<TItem> enumerable, string delimiter)
{
return string.Join("", enumerable.Select(x => x.ToString() + separator).ToArray());
}
You could also use .Aggregate to do this without an extension method.