Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C#, is there an "easy" way to perform string.Join on complex type list?

Tags:

string

c#

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)?

like image 793
Chaddeus Avatar asked Aug 16 '12 13:08

Chaddeus


2 Answers

using System.Linq  string.Join(",", member.Roles.Select(r => r.Name)) 
like image 59
Maarten Avatar answered Sep 28 '22 04:09

Maarten


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); 
like image 40
Nikhil Agrawal Avatar answered Sep 28 '22 03:09

Nikhil Agrawal