class String
contains very useful method - String.Join(string, string[])
.
It creates a string from an array, separating each element of array with a symbol given. But general - it doesn't add a separator after the last element! I uses it for ASP.NET coding for separating with "<br />
" or Environment.NewLine
.
So I want to add an empty row after each row in asp:Table
. What method of IEnumerable<TableRow>
can I use for the same functionality?
There is no built in method to do that, you should roll your own.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With