I would say write your own extension method:
public static IEnumerable<T> Order<T, TKey>(this IEnumerable<T> source, Func<T, TKey> selector, bool ascending) { if (ascending) { return source.OrderBy(selector); } else { return source.OrderByDescending(selector); } }
Then you can simply write:
lst = lst.Order( s => s.Letter, isAscending );
As for specifying the method name: I hope this does not come off the answer to copy, but I think you should use the select function instead of passing in a string. Going along a string route doesn't really allow you to type or improve clarity (is the "letter" really much faster or clearer than s => s.Letter ?), And only makes your code thicker (do you need to either support some kind of mapping from strings for selection functions or write your own parsing logic for converting between them) and perhaps more fragile (if you go through the last route, there will be a rather high probability of errors).
If you intend to take a string from user input to set up sorting, of course, you have no choice, so feel free to ignore my disappointing comments!
Change Since you are accepting user input, here is what I mean by matching:
class CustomSorter { static Dictionary<string, Func<IMyClass, object>> Selectors; static CustomSorter() { Selectors = new Dictionary<string, Func<IMyClass, object>> { { "letter", new Func<IMyClass, object>(x => x.Letter) }, { "number", new Func<IMyClass, object>(x => x.Number) } }; } public void Sort(IEnumerable<IMyClass> list, string sortField, bool isAscending) { Func<IMyClass, object> selector; if (!Selectors.TryGetValue(sortField, out selector)) { throw new ArgumentException(string.Format("'{0}' is not a valid sort field.", sortField)); }
The foregoing is clearly not as smart as dynamically generating expressions from strings and calling them; and this can be considered strength or weakness depending on your preferences, as well as the team and culture of which you are a part. In this particular case, I think I would vote for a manual display, because the dynamic expression route feels overly designed.