0

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");
Jason Thuli
  • 736
  • 2
  • 8
  • 23
  • Look at the definition of `OrderBy`, that will tell you exactly what your functions need to return (hint: `Expression`s!) – DavidG Apr 09 '18 at 12:55
  • We're using EF-Core but, as an hint. We're returning IQueryable from our methods and chain our filters and sorters this way. – user743414 Apr 09 '18 at 12:56
  • Of course you can. Just pass query you are building other queries on as parameter to your methods. – hcerim Apr 09 '18 at 12:56
  • 1
    look at this question posted yesterday, I used Expressions in my answer https://stackoverflow.com/a/49723639/6197785 – mshwf Apr 09 '18 at 13:02
  • PredicateBuilder may do it. Using expressions: http://www.albahari.com/nutshell/predicatebuilder.aspx – P.Brian.Mackey Apr 09 '18 at 13:04

0 Answers0