I would like to have my comparison functions accessible by using a key. This is what I have tried. I think my problem is how I’m declaring the type for the dictionary value.
internal static int CompareUsersByEmail(MembershipUser a, MembershipUser b)
{
// imagine null checking happening here.
return string.Compare(a.Email, b.Email, true);
}
public static void Sort(List<MembershipUser> list, string expression) {
// I can do this
list.Sort(CompareUsersByEmail);
// but not this
Dictionary<string, Func<MembershipUser, MembershipUser, int>> compareFns;
compareFns = new Dictionary<string, Func<MembershipUser, MembershipUser, int>>();
compareFns["Email"] = CompareUsersByEmail;
list.Sort(compareFns[expression]); // where expression would be "Email"
}
Is this possible?
Change your dictionary type to:
I believe it will then work with no other changes. The method group conversion to
Comparison<MembershipUser>will still work, and now you can callList<T>.Sort(Comparison<T>).