C
C#2y ago
cdbus

❔ ✅ Get name of assigned property in an Expression

I am (partially for fun) writing the following method:
void BulkMerge<T, TConstraint>(
IEnumerable<T> entities,
Expression<Func<T, TConstraint>> constraintSelector
) {
//
}
void BulkMerge<T, TConstraint>(
IEnumerable<T> entities,
Expression<Func<T, TConstraint>> constraintSelector
) {
//
}
Here is how I intend to call it:
BulkMerge(accounts, (a) => new { AccountID = a.Id });
BulkMerge(accounts, (a) => new { AccountID = a.Id });
I'd like to parse the Expression argument above such that I have
var maps = constraintSelector.ExtractMaps();
var maps = constraintSelector.ExtractMaps();
Where ExtractMaps is an extension method that returns this structure (denoted in JSON for clarity)
[ { "Source": "Id", "Destination", "AccountID" } ]
[ { "Source": "Id", "Destination", "AccountID" } ]
Is this possible in C#?
5 Replies
Anton
Anton2y ago
your constraint selector is an expression tree. go through the individual nodes and figure out what you got there should be a visitor base class for that, or just go through them manually you are expecting a certain structure after all
cdbus
cdbusOP2y ago
🦥 fine... Thank you
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
cdbus
cdbusOP2y ago
@AntonC just following up, got this working perfectly 👍 Wrote an ExpressionVisitor subclass, and the rest is history
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server