How to join as a string a property of a class?

前端 未结 1 1060
南笙
南笙 2021-01-04 04:08

\"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:

L         


        
1条回答
  •  北海茫月
    2021-01-04 04:56

    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(this IEnumerable source, Func func)
        {
            return ToDelimitedString(source,",",func);
        }
    
        public static string ToDelimitedString(this IEnumerable source, string delimiter, Func func)
        {
            return String.Join(delimiter, source.Select(func).ToArray());
        }
    }
    

    Usage:

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

    .....

            var list = new List();
            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);
    

    0 讨论(0)
提交回复
热议问题