Say I have a Dictionary object which contains many instances of an object called SomeObject and each SomeObject has properties named Property1 and Property2. Now say I have a method which can return a new Dictionary sorted by Property1. However, I’d like to generalize that method such that I can tell it which property to sort by.
For example, to do this, I know I could easily have two separate methods such as:
public Dictionary<string, SomeObject> SortByProp1(Dictionary<string, SomeObject> dict) { ... }
public Dictionary<string, SomeObject> SortByProp2(Dictionary<string, SomeObject> dict) { ... }
But, I’m wondering if it’s possible to combine these into one method in which I can give a parameter to identify which method to return? I don’t know of a way to generalize a property like that…
Note: I do realize I could always use something like an if-statement which could be based on a string of the property name, but that doesn’t seem like a very elegant, acceptable answer much better than just having two separate methods to begin with.
The method you seek is built into the
IEnumerable<T>interface, and isOrderBy, though it might not work out as smothly for a Dictionary as you might like.Dictionary<TKey, TValue>implementsIEnumerable<KeyValuePair<TKey, TValue>>, so its OrderBy method takes a lambda expression which itself takes aKeyValuePair<TKey, TValue>, and returns a selector method that describes what you’re sorting by.For example, if you have
Dictionary<int, Customer>, this will return to you anIEnumerable<KeyValuePair<int, Customer>>sorted by customer name:Then to get just the customers themselves in this sorted order, you’d say: