Search code examples
c#linqextension-methodsienumerable

An analog of String.Join(string, string[]) for IEnumerable<T>


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?


Solution

  • 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())