I am working on a filtering function. The filter will be an expression tree build by an user. There will be about 30 fields the user can use for filtering. I think the best way is to create the object model with indexer and to access required values by index of enum type.
See this example:
enum Field
{
Name,
Date,
}
class ObjectModel
{
object this[Field Key]
{
get
{
//...
return xx;
}
}
}
I would like to ask how can I access an indexer from an expression tree.
The indexer is a simple property, normally called
Item
. This means, you can access the indexer like any other property by using its name.The name of the indexer property can be changed by the implementor of the class by means of the
IndexerName
attribute.To reliably get the actual name of the indexer property, you have to reflect on the class and obtain the
DefaultMember
attribute.More information can be found here.
I'll post a complete example on how to use an indexer:
To read from the indexer the
IndexExpression
contains directly the value of the indexed property. To write to it we must useExpression.Assign
. Everything else is quite vanillaExpression
. As written by Daniel the Indexer is normally called "Item". Note thatExpression.Property
has an overload that accepts directly the name of the indexer (so"Item"
), but I chose to find it manually (so it can be reused). I have even put an example on how to use LINQ to find the exact overload of indexer you want.Just as a curiosity, if you look on MSDN for example for Dictionary, under Properties you'll find Item