class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
List<Person> theList = populate it with a list of Person objects
How can I get a string which contains all the FirstName of the objects in the list separated by a comma. Eg: John,Peter,Jack
A basic solution would be to iterate through each object but I'm sure there is a one-line solution.
Thanks.
Update (as of .NET 4)
string.Join
now has an overload which takes an IEnumerable<string>
- yay!
string.Join(",", theList.Select(p => p.FirstName));
For .NET versions below 4.0 (older):
string.Join(",", theList.ConvertAll(person => person.FirstName).ToArray());
Breaking it down into component parts:
List<T>.ConvertAll
converts a List<T>
to another type - in this case a List<string>
.
ToArray()
converts the List<string>
to a string[]
.
string.Join()
writes an array of strings (the second parameter) as a single string, separated by the first parameter.
You could also use a query extension method
string output = theList.Select(p => p.FirstName).Aggregate((progress, next) => progress + ", " + next);
This will avoid having to create an array.
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