I'm trying apply query from one collection to another. Sample of my test:
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
Expression sourceExpression = Amazings().Where(x => x.Name.Equals("Kasa")).AsQueryable().Expression;
Expression<Func<Amazing, bool>> predicate = Expression.Lambda<Func<Amazing, bool>>(sourceExpression, Expression.Parameter(typeof(Amazing)));
var col2 = Amazings().Where(predicate.Compile());
}
private IEnumerable<Amazing> Amazings()
{
var amazings = new List<Amazing>
{
new Amazing
{
Name = "Kasa",
},
new Amazing
{
Name = "Ma@p2a"
}
};
return amazings;
}
class Amazing
{
public string Name { get; set; }
}
}
What is wrong? When I run this test in debug I get the exception:
You can not use expressions such as „System.Linq.EnumerableQuery`1[UnitTestProject1.UnitTest1+Amazing]” for the return type „System.Boolean”.
If I run this without parameter I got exception that I don't have parameters.
If I change parameter to boolean type I got exception: you can't use element bool type for delegate parameter type Amazing...
I tested few more options but nothing works.
Also I found that the key may by casting Expression to: MethodCallExpression but it's not or I can't figurate how.
I tried with somothing like this:
MethodCallExpression e = query.Expression as MethodCallExpression;
MemberExpression memberExpression = (MemberExpression)e.Object;
Expression<Func<Amazing, bool>> getCallerExpression = Expression<Func<Amazing>>.Lambda<Func<Amazing, bool>>(memberExpression);
Unfortunately memberExpression is null.
I searched the web and the only thing I found it's a tip: ~"don't do this".
How can I achieve my goal?
答案 0 :(得分:3)
答案 1 :(得分:2)