I have a LINQ TO SQL query which retrieves all the users along with their roles:
var userRoles = from u in db.GetTable<User>()
join ur in db.GetTable<UserRole>()
on u.UserID equals ur.UserID
join r in db.GetTable<Role>()
on ur.RoleID equals r.RoleID
orderby u.UserID
select new
{
u.UserID,
r.RoleName
};
A user in the system can have multiple roles. The result of this query (in a table format) looks like:
1 Admin
1 Employee
2 Employee
3 Employee
How can I re-write this query to return all user roles as comma separated values like:
1 Admin, Employee
2 Employee
3 Employee
Hey Kumar, I created a small console app to mimic the data I believe you have. I think it exhibits the behavior you are looking for though. It’s not the greatest code in the world, but I think the algorithm is the point. I just threw together a quick override of ToString() to display the data correctly.
The main change I did was to create a defined class for the data to be displayed, and break the linq query into two separate pieces: