"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'
The join() string method returns a string by joining all the elements of an iterable (list, string, tuple), separated by a string separator.
The string class is marked sealed because you are not supposed to inherit from it.
There are the two properties of String class : Chars[Int32]: Used to get the Char object at a specified position in the current String object. In C#, the Chars property is an indexer. Length: Used to get the number of characters in the current String object.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With