Is it possible to do something like this when calling Linq-To-Entities?
// Makes a call to the database getting a list of people
public Person[] GetPeople(string sortBy) {
var people = context.Persons.AsQueryable();
// Determining which private method to call for sorting
var sortBy = null;
switch (sortBy) {
case "name":
sortBy = SortByName; // Should this actually execute the function? Or just be a reference to the function?
break;
case "age":
sortBy = SortByAge;
break;
case "hairColor":
sortBy = SortByHairColor;
break;
}
// Return sorted results
return people.OrderBy(sortBy).ToArray();
}
// Sorting by the person's name
private WHATGOESHERE SortByName() {
return q => q.Name;
}
// Sorting by the person's age
private WHATGOESHERE SortByAge() {
return q => q.DateOfBirth;
}
// Sorting by the person's hair color
private WHATGOESHERE SortByHairColor() {
return q => q.HairColor;
}
The reason I need to separate these is because I have multiple methods with different logic returning different subsets of people. And, within each method, I have conditional logic determining the sorting. I seem to be duplicating the sorting logic pretty often.
I would also like to be able to sort by multiple methods, like this:
people = people.OrderBy(SortByName).ThenBy(SortByAge).ThenByDescending(SortByHairColor);
I found this thread, but I couldn't quite get it to work.
Any help is appreciated.
Edit #1: I forgot to mention that I am not interested in dynamic queries like:
.OrderBy("Name, DateOfBirth, HairColor DESC");