How to sort a list of a class by property using LINQ when the name of the property comes from input
So, im learning c# and im trying to solve an exercise.
The issue im facing is, i have a class that has 3 int properties, for example population, surface and diameter, and i want to get from a list of that class, the objects with the max and the min of one of those properties chosen from an input on the console. So, if i write in the console "population", filter the list and retrieve the ones with the most and least population. I thought about using LINQ OrderBy and then pick the first and last items, but im blanking out on how to use the input i get to do that, since i get a string like "population" from the console and i can't use it in OrderBy(x => x.population). I feel like its probably really stupid im forgetting but my head is so burned right now that i can't come up with anything
6 Replies
Reflection... maybe
Or a switch expression is how I handle it
EF example
Linq is a viable option.
Linq operations are lazy. This means that they are not execute instantly, only once you start iterating over the result.
The sortedLazy does not contain any sorted items at this moment. Only a definition of how the original myData is to be changed based on the LINQ expressions used.
So you could use a switch expression to solve your issue. Min max based on what you want, save the result somewhere. And later do a toArray or something like that
after i read your example i realized i forgot to add something important, im using reflection to get the name of the properties and then show them as the possible option to write in the console because im trying to make this work with a List of different classes with different property names. thats why maybe the switch statement wasnt an option i think? i though i maybe having to use reflection again but i dont know how i would do it haha
Alternatively, you could use source generators maybe
That way you could mark a class as
[Sortable]
or something and generate the possible lambdas for ithmm, i'll see what i can come up with, thanks for the advice, i'll try to think it with a fresher head later and maybe even find a different approach
Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.