Let's say I have a method:
bool myMethod(int a)
{
//return a bool
}
So let's say I the following
// assume a has prop1 and prop2 both ints
var mySelection = from a in myContainer
where a=somecondition
select new {
a.prop1,
myMethod(a.prop2)
};
Is there really no way to run myMethod in the anonymous type declaration? Is there some sort of trick?
Can I put an anonymous method in there to return the equivalent of myMethod(a.prop2)?
Well lets separate this into LINQ to Objects and LINQ to Entities
In LINQ to Object the above fails because the compiler doesn't know what the Property name is, if you change it to this:
var mySelection = from a in myContainer
where a=somecondition
select new {
a.prop1,
prop2 = myMethod(a.prop2)
};
It will work in LINQ to Objects
However the Entity Framework won't be able to translate the method call (unless it is a function known to the EF like a Model Defined Function, EdmMethods or SqlMethods) so you'll have to rewrite that query like this:
var mySelection = from a in myContainer
where a=somecondition
select new {
a.prop1,
a.prop2
};
var myResults = from a in mySelection.AsEnumerable()
select new {a.prop1, prop2 = myMethod(a.prop2)};
This pulls what you need out the database, and then using the AsEnumerable() call turns the call to myMethod into something processed by LINQ to Objects rather than LINQ to Entities
Hope this helps
Alex
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With