Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 860
abatishchev Avatar asked Jun 14 '09 19:06

abatishchev


4 Answers

There is no built in method to do that, you should roll your own.

like image 55
driis Avatar answered Oct 11 '22 16:10

driis


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.

like image 29
Scott Weinstein Avatar answered Nov 13 '22 15:11

Scott Weinstein


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())
like image 8
spender Avatar answered Nov 13 '22 16:11

spender


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.

like image 8
Ian Mercer Avatar answered Nov 13 '22 15:11

Ian Mercer