C# make a Dictionary of Lambdas

c# expression-trees lambda

Question

I'm having a trouble defining a Dictionary for quick accessing Lambda Expressions.

Let's suppose we have a well-known class like this:

class Example
{
    public string Thing1;
    public DateTime Thing2;
    public int Thing3;
}

What a want to do is something like this:

var getters = new Dictionary<string, IDontKnowWhatGoesHere>();
getters.Add("Thing1", x => x.Thing1);
getters.Add("Thing3", x => x.Thing3);

Is this possible?

Edit:

This is my use case for this object:

List<Example> array = new List<Example>();

// We actually get this variable set by the user
string sortField = "Thing2";

array.Sort(getters[sortField]);

Many thanks for your help.

Accepted Answer

You've got a couple of options. If, as in your example, the things you want to get are all the same type (i.e. String), you can do

var getters = new Dictionary<string, Func<Example, String>>();

However, if they're different types, you'll need to use the lowest common subclass, which in most cases will be Object:

var getters = new Dictionary<string, Func<Example, object>>();

Note that you'll then need to cast the return value into your expected type.


Popular Answer

var getters = new Dictionary<string, Expression<Func<Example, object>>>();

However, string Thing1 should be public.



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why