The string.Join method can come in handy when you want a comma separated list of strings. However, there's a major limitation. To use it, you must provide a one-dimensional string array. What if you have a collection of objects and you want to "Join" a property on the objects (e.g., a comma separated list of IDs).
Well, since I couldn't find anything within the framework that would do this for me, I wrote an extension method that meets my need.
Updated from suggestion in the comments.
public static string Join<T>( this IEnumerable<T> target, Func<T, object> valueSelector )
{
StringBuilder result = new StringBuilder();
foreach( T item in target )
{
result.Append( valueSelector(item).ToString() );
result.Append( "," );
}
result.Length--; //remove the trailing comma
return result.ToString();
}
This will take any Generic Enumerable and Join the string representation based on the value selector you provide.
Here is an example of how to use it:
public class Child
{
public int Id { get; set; }
public string Name { get; set; }
// ...
}
public class Parent
{
public int Id { get; set; }
public string Name { get; set; }
public List<Child> Children;
// ...
public string ChildIds
{
get { return Children.Join( child => child.Id ); }
}
public string ChildNames
{
get { return Children.Join( child => child.Name ); }
}
}
Cheers.