views:

38

answers:

1

"I have a List of objects with a property "CustomizationName".

I want to join by a comma the values of that property, i.e.; something like this:

List<MyClass> myclasslist = new List<MyClass>();
myclasslist.Add(new MyClass { CustomizationName = "foo"; });
myclasslist.Add(new MyClass { CustomizationName = "bar"; });
string foo = myclasslist.Join(",", x => x.CustomizationName);
Console.WriteLine(foo); // outputs 'foo,bar'
+4  A: 
string foo = String.Join(",", myClasslist.Select(m => m.CustomizationName).ToArray());

If you want, you can turn this into an extension method:

public static class Extensions
{
    public static string ToDelimitedString<T>(this IEnumerable<T> source, Func<T, string> func)
    {
        return ToDelimitedString(source,",",func);
    }

    public static string ToDelimitedString<T>(this IEnumerable<T> source, string delimiter, Func<T, string> func)
    {
        return String.Join(delimiter, source.Select(func).ToArray());
    }
}

Usage:

public class MyClass
{
    public string StringProp { get; set; }
}

.....

        var list = new List<MyClass>();
        list.Add(new MyClass { StringProp = "Foo" });
        list.Add(new MyClass { StringProp = "Bar" });
        list.Add(new MyClass { StringProp = "Baz" });

        string joined = list.ToDelimitedString(m => m.StringProp);
        Console.WriteLine(joined);
BFree