Let's say I have this object:
public class Role { public string Name { get; set; } public string Slug { get; set; } public DateTime DateAssigned { get; set; } ... }
A member can have multiple roles: member.Roles = List<Role>();
If I wanted to join the member's roles into a comma separated list of the role names, is there an easy way (similar to string.Join(",", member.Roles);
- which doesn't work because a role is a complex type)?
using System.Linq string.Join(",", member.Roles.Select(r => r.Name))
If you only want the Name property, then other answers are good
But if you have more properties, adjust your ToString()
to match:
public override String ToString() { return String.Format("Name: {0}. Slug : {1}", Name, Slug); }
etc. and then call it as
String.Join(", ", member.Roles);
You wouldn't need to call
String.Join(", ", member.Roles.Select(x => x.ToString())
as it would be called internally by object inside String.Join()
, so if you override ToString()
, you just call
String.Join(", ", member.Roles);
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