如何将类的属性作为字符串连接起来?

20

我有一个对象列表,其中包含一个名为“CustomizationName”的属性。

我想要通过逗号将该属性的值连接起来,例如:

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'
1个回答

43
string foo = String.Join(",", myClasslist.Select(m => m.CustomizationName).ToArray());

如果你愿意,你可以把它转化为扩展方法:

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());
    }
}

使用方法:

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);

1
很好的答案,但你不需要使用.ToArray()这一部分。 - David Thielen
@DavidThielen 这个答案是从'09年,5年前的,当时还没有 .Net 4.0。在旧版本的 .Net 中,你不能将 IEnumerable 传递给 String.join,它必须是一个数组。 - BFree
需要使用 System.Linq(我知道这可能很明显,但我不得不寻找它)。 - geriwald

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接