score:2

Yes, you can declare a function, but you can't define it to return a property of the anonymous type that is currently being declared-- if you were to use this, for example, the lambda would capture the value of this in the declaring context (the class that contains the code that is executing the LINQ). You can however capture the values that are being used to initialize the anonymous class (as I do in the example below).

Note that this is not the same as giving the anonymous class a method. Anonymous classes can only have read-only, immutable properties. In this case, your anonymous class will still have the original ToString() method inherited from object. This may make it tricky to distinguish the function held in the ToString property from the ToString() method, so maybe you should use a different name.

Also, you forgot the new keyword before Func.

var personsByCity = from p in people join c in cities on p.CityId equals c.Id
    select new 
    {
        PersonName = p.Name, 
        CityName = c.Name,
        ToString = new Func<string>( () => { 
            return c.Name + "/" + p.Name; 
        })
    };

Related Articles