Assigning property of anonymous type via anonymous method

GarbageGuy picture GarbageGuy · Mar 3, 2010 · Viewed 8.9k times · Source

I am new in the functional side of C#, sorry if the question is lame.

Given the following WRONG code:

var jobSummaries = from job in jobs
                   where ...
                   select new 
                   {
                        ID = job.ID,
                        Description = job.Description,
                        FileName = (job) => {
                                  // primitive logic not 
                                  // worth to become a named method
                                  try { return job.Files[0].LocalName); }
                                  catch { return null as string; }
                                 }
                   };

This code produces the following justified compiler error:

cannot assign lambda expression to anonymous type property

The code above would set the delegate to the FileName property. But that is not my aim. I want the code work like this but without naming the method:

var jobSummaries = from job in jobs
                   where ...
                   select new 
                   {
                        ID = job.ID,
                        Description = job.Description,
                        FileName = this.ExtractFileName(job)
                   };

...
private string ExtractFileName(Job job)
{
     try { return Path.GetFileName(job.Files[0].LocalName); }
     catch { return null as string; }
}

Any suggestions?

Answer

Jens picture Jens · Mar 3, 2010

To call an anonymous function directly, this works:

int result = new Func<int, int>( (int i) =>{ return i + 5; } ).Invoke(3);
// result = 8

But I agree, int result = (i => i + 5)(3); would be way cooler =)