I'm trying to dynamically remove an item from an IEnumerable
using reflection.
Currently my code looks like this:
// get the value from the object
var targetPropertyValue = targetProperty.GetValue(objectToApplyTo, null);
// invoke singleOrDefault
var elementToRemove = genericSingleOrDefaultCall.Invoke(null, new [] { targetPropertyValue, singleOrDefaultLambda.Compile() });
// get the except-call
var genericExceptCall = typeof(Enumerable)
.GetMethods(BindingFlags.Public | BindingFlags.Static)
.Single(mInfo => mInfo.Name == nameof(Enumerable.Except) && mInfo.GetParameters().Length == 2)
.MakeGenericMethod(sourceType);
// get the cast-call
var genericCastCall = typeof(Enumerable).GetMethod(nameof(Enumerable.Cast)).MakeGenericMethod(sourceType);
// cast to the correct type
var castedEnumerable = genericCastCall.Invoke(null, new object[] { Enumerable.Repeat(elementToRemove, 1) });
// create a new ienumerable without that element
var exceptResult = genericExceptCall.Invoke(null, new[] {targetPropertyValue, castedEnumerable });
Checking via the debbugger, all my variables do have the corret type when invoking the Except
-call. However, the element is not being removed from the original enumeration. So my best guess is, that elementToRemove
is a newly created object and therefore not part of the source-enumeration. So the Except
does not match the element. But how can it be done instead?
Aucun commentaire:
Enregistrer un commentaire