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.
1: public static string Join<T>( this IEnumerable<T> target, Func<T, object> valueSelector )
2: {
3: StringBuilder result = new StringBuilder();
4: foreach( T item in target )
5: {
6: result.Append( valueSelector( item ).ToString() );
7: result.Append( "," );
8: }
9: result.Length--;
10: //remove the trailing comma
11: return result.ToString();
12: }
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:
1: public class Child
2: {
3: public int Id { get; set; }
4: public string Name { get; set; }
5: // ...
6: }
7: public class Parent
8: {
9: public int Id { get; set; }
10: public string Name { get; set; }
11: public List<Child> Children;
12: // ...
13: public string ChildIds
14: {
15: get { return Children.Join( child => child.Id ); }
16: }
17: public string ChildNames
18: {
19: get { return Children.Join( child => child.Name ); }
20: }
21: }
Cheers.