Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# make a Dictionary of Lambdas

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.

like image 210
Adrian Salazar Avatar asked Jul 30 '13 13:07

Adrian Salazar


1 Answers

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.

like image 126
RoadieRich Avatar answered Sep 29 '22 23:09

RoadieRich