Data Browser - Viewing Site  Sector 23 Code Bank Logged in as:  Guest  




           


LINQ function to concatenate elements into a string
Found this on MSDN where they used it to merge openXML element text; but it looks infinitely useful for other purposes.

/// <summary>
/// Concatenate elements
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="source"></param>
/// <param name="func"></param>
/// <returns></returns>
public static string StringConcatenate<T>(this IEnumerable<T> source,
Func<T, string> func)
{
StringBuilder sb = new StringBuilder();
foreach (T item in source)
sb.Append(func(item));
return sb.ToString();
}

/// <summary>
/// Concatenate elements
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="source"></param>
/// <param name="func"></param>
/// <param name="separator"></param>
/// <returns></returns>
public static string StringConcatenate<T>(this IEnumerable<T> source,
Func<T, string> func, string separator)
{
StringBuilder sb = new StringBuilder();
foreach (T item in source)
sb.Append(func(item)).Append(separator);
if (sb.Length > separator.Length)
sb.Length -= separator.Length;
return sb.ToString();
}

Created By: amos 4/28/2015 9:03:05 AM