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?
In LINQ, select clause generates anonymous type so that in a query you can include properties that are not defined in the class.
Essentially an anonymous type is a reference type and can be defined using the var keyword. You can have one or more properties in an anonymous type but all of them are read-only. In contrast to a C# class, an anonymous type cannot have a field or a method — it can only have properties.
An anonymous method is a method which doesn't contain any name which is introduced in C# 2.0. It is useful when the user wants to create an inline method and also wants to pass parameter in the anonymous method like other methods.
Limitations of Anonymous MethodsAny unsafe codes cannot be accessed inside anonymous methods. There cannot be jump statements such as goto, break or continue inside anonymous methods. Anonymous methods cannot be used on the left side of the is operator.
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 =)
As far as I know, you can't inline lambda expressions like that because a lamda expression is an instance itself (of the type Expression<Func<T>>
or similar).
However, you can do this (updated with calculation of fileName, since this is now provided by the OP):
var jobSummaries = from job in jobs
where ...
let fileName = job.Files.Select(f => f.LocalName).FirstOrDefault()
select new
{
ID = job.ID,
Description = job.Description,
FileName = fileName
};
Notice the use of the let
keyword, that lets you extract the filename from the job
variable directly inside the LINQ expression.
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