I’ve written an extension method that can take an arbitrary number or OrderBy()’s and apply them recursively….
It’s probably best I show an example:
public static IEnumerable<User> ApplyOrdering(this IEnumerable<User> users,
int index,
params Func<User, string>[] sorts)
{
if(index == sorts.Length)
return users;
users = users.OrderBy(sorts[index]);
index++;
return users.ApplyOrdering(index, sorts);
}
// And it's called like this:
void Example()
{
var users = GetUnsortedUsers();
var sortedUsers = users.ApplyOrdering(0, u => u.DisplayName,
u => u.Username,
u => u.Email);
}
Not so much a question, but I want to know if this can be done in a better, more elegant fashion?
For one thing, I don’t like having to declare the starting index in the method call. Another possible nitpick is having to call .ApplyOrdering() that final time just to return the users.
Whatta ‘ya think?! I’d love to see some of the clever solutions you C# gurus out there come up with!
EDIT: I know some of you will point out that it is better, and more expressive to simply write the queries like this:
var orderedUsers = users.OrderBy(u => u.DisplayName)
.ThenBy(u => u.Username)
.ThenBy(u => u.Email);
But in my scenario, the amount and type of filters is not always the same, so I needed a general purpose solution that could accomodate any number of filters.
Currently it’s broken – it will effectively apply the ordering backwards. I suspect you want: