views:

281

answers:

2

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)?

+1  A: 

I don't think there is a way to call out to a method from an anonymous initializer. Even if there were, it probably wouldn't perform very well.

If you need to create a result set that requires additional processing, I would create a concrete class.

Dave Swersky
+4  A: 

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

Alex James
Tried this, doesn't work: "Anonymous type members must be declared with a member assignment, simple name or member access."
Dave Swersky
Well it 'works on my machine'!
Alex James
OK, got it. Works.
Dave Swersky