I have two ifs in a function that sorts users by their roles, the users that access an application. Each user is an object with properties like name, password, which are just simple strings, but each user has an inner object, named Role that has a property Name, which is a string. The code looks something like:
public GetUsersSorted(string sortBy)
{
if(sortBy=='roles')
{
usersCollection = get the users, but not sorted by anything
}
else
{
usersCollection = get users sorted sorted by something else
}
items = mapUsersToDTO(usersCollection)
if(sortBy=='roles')
{
items = sortUsersInMemory(items)
}
}
private mapUsersToDTO(List usersSorted)
{
foreach(var item in usersSorted)
{
item.Roles = item.Roles.OrderBy(i => i.Name).ToList(); //here I sort the roles inside the user
}
usersSorted = usersSorted.OrderBy(b => b.Roles.First().Name()).ToList();
return usersSorted;
}
How can I sort them more efficiently, based on the Name of their Role? This works too but, I sort them based only on the first role, and I want to sort them based on all the names of their roles
Sounds like you've got a list in your list and you want the nested list also ordered.
users.Select(x=>x.Roles.OrderBy(y=>y.Name).ToList())
.OrderBy(x=>x.Name).ToList();
This orders the internal list, then orders the outer list.
If you posted some actual code or maybe the model for your data, I could tailor that solution better.