2009-12-30 6 views
11

"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' 

उत्तर

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

उपयोग::

आप चाहते हैं, आप एक विस्तार विधि में इस बंद कर सकते हैं

.....

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

आप एक्सटेंशन उदाहरण के लिए बोनस अंक मिलना चाहिए। – Snekse

+0

महान उत्तर लेकिन आपको .ToArray() भाग की आवश्यकता नहीं है। –

+0

@ डेविड थिलेन यह जवाब '0 9, 5 साल पहले से पहले था, नेट 4.0 बाहर था। .Net के पुराने संस्करणों में, आप String.join पर IENumerable पास नहीं कर सके, इसे एक सरणी होना था। – BFree

संबंधित मुद्दे