Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

string

c#

list

"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'
like image 520
esac Avatar asked Dec 30 '09 05:12

esac


People also ask

What does string join do?

The join() string method returns a string by joining all the elements of an iterable (list, string, tuple), separated by a string separator.

Can we inherit the properties of string class?

The string class is marked sealed because you are not supposed to inherit from it.

What is string property in C#?

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.


1 Answers

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);
like image 128
BFree Avatar answered Sep 20 '22 03:09

BFree