0

I have a database query providing me IQueryable object where T is anonymous data type like this:

var baseListQuery = (<...> select new {
    note = n, // class Note
    triggers = grp // class Trigger
})

Now I would like to sort this by different properties of Note (e.g. Note.Title) but my Note class can contain plenty of different properties. Property to be used as sorting element can be changed externaly and information about which one to use I will receive as a simple string. Currently I am using switch-case statement to evaluate received string and then select appropriate property to sort:

switch(SortBy) {
    ...
    case "Title": baseListQuery = baseListQuery.OrderBy(p => p.note.Title); break;
    ...
}

However, I am wondering if it is possible to to it in more general way, using reflection? I would like to check if Note contains property with the name of received string and if so, sort results appropriately. I have tried something like this:

var baseQueryType = baseListQuery.GetType();
var member = (baseQueryType.GetGenericArguments()[0]).GetProperty("note");
var member2 = member.PropertyType.GetProperty("Title"); // I would like to use GetProperty(SortBy);
baseListQuery = baseListQuery.OrderBy(p => member2);

Which will raise exception when calling for example baseListQuery.Count():

System.NotSupportedException: 'Unable to create a constant value of type 'System.Reflection.PropertyInfo'. Only primitive types or enumeration types are supported in this context.'

Is it possible to do this with reflection, and if so, can somebody explain me, what am I doing wrong?

esgaldir
  • 823
  • 9
  • 11
  • There are various implementations of Dynamic Linq that do things similar to what you want. Search for them in nuget. – xanatos Jun 11 '18 at 12:22
  • 2
    [This answer](https://stackoverflow.com/a/7265354/1663001) is a good way to do this without resorting to Dynamic Linq – DavidG Jun 11 '18 at 12:23
  • @DavidG Just tried this with a little modification for properties nested deeper in hierarchy and seems that proposed approach solved my problem. What a nice solution. Thank You. – esgaldir Jun 11 '18 at 14:43
  • Great to hear. Not my solution though, be sure to vote on the link in question :) – DavidG Jun 11 '18 at 14:45

0 Answers0