Monday, 9 September 2013

Use Where iEnumerable extension with reflection

Use Where iEnumerable extension with reflection

I have a list of items on a datagrid, the items type are only known at
runtime, so my datagrid is filled by an iEnumerable< object >, and I need
to find a certain register on this datagrid by using the Where Extension
method of iEnumerable< T >. But when the Where extension is invoked
through reflection, it throws an InvalidCastException
My code :
var items = dataGrid.ItemsSource;
var method = this.GetType().GetMethod("GenerateExpressionEqualsValue");
var genericMethod = method.MakeGenericMethod(registroAtual);
//resultExpression is set to (param_0 => param_0.fieldOftable ==
textloc);
var resultExpression = genericMethod.Invoke(this, new object[] {
regSel, textloc });
var whereMethodFound = typeof(System.Linq.Enumerable)
.GetMethods(BindingFlags.Static | BindingFlags.Public)
.Where(mi => mi.Name == "Where")[0];
var whereMethod = whereMethodFound.MakeGenericMethod(registroAtual);
//Exception is thrown here saying i cannot convert from
'System.Linq.Enumerable+<CastIterator>d__b1`1[System.Object]' To
'System.Collections.Generic.IEnumerable`1[Model.TableX]'.
var ret = whereMethod.Invoke(items, new object[] {items, resultExpression });

No comments:

Post a Comment