I mainly try to make this one , but I donβt know what T is, so I build things using reflection and expression trees.
Type itemType = typeof(Book);
ParameterExpression predParam = Expression.Parameter(itemType, "p");
Expression left = Expression.Field(predParam, itemType.GetField("AuthorName"));
Expression right = Expression.Constant("Jon Skeet", typeof(string));
Expression equality = Expression.Equal(left, right);
Delegate myDelegate = Expression.Lambda(equality, new ParameterExpression[] { predParam }).Compile();
Type genericPredicateType = typeof(Predicate<>);
Type constructedPredicateType = genericPredicateType.MakeGenericType(new Type[] { itemType });
object predicateInstance = Activator.CreateInstance(constructedPredicateType, new object[] { myDelegate });
Basically, I have List<Book>, which I am trying to reflect, and Invokeits method Find. The method Findis required Predicate<Book>instead Func<Book, bool>, and I hit my head about it several times.
Edit: here is the first part of the error trace:
System.MissingMethodException: Constructor on type 'System.Predicate`1[[MyProject.Book, MyProject, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]' not found.
source
share