Anonymous Person
Anonymous Person

Reputation: 1540

Lambda expression error

I have an issue that's eating my head for the past couple of days. I am unable to find a solution.

I am trying to find the occurrence of '\' in a string using lambda expressions. Here's the code:

Microsoft.Office.Interop.Excel.Range labelSupportTopic = (Microsoft.Office.Interop.Excel.Range)xlWorkSheet.Cells[resultRange.Row, 29];
int count = labelSupportTopic.Text.ToString().Count(c => c == '\\'); 

I am getting the date from an Excel sheet, therefore the Interop reference.

What's bothering me is that this code is copied and pasted from an exact same VS project whose most of the code I lost somehow. I was lucky to have some part and this was one of it. Regardless, on my other VS project (the one whose code I lost), I am able to Build and it looks fine. But my current project, the one I built from scratch, it throws an error on Build. This entire section, the one that contains this logic is lifted off from my old project (which Builds fine). The error reads "Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type" I searched the internet but I was unable to find a solution.

Can you help, please?!

Upvotes: 1

Views: 590

Answers (1)

Slai
Slai

Reputation: 22886

int count = (labelSupportTopic.Text as string).Count('\\'.Equals);

Because the type of .Text is dynamic, the type of .ToString() is also dynamic, and the type of c in the lambda expression can't be inferred.

In earlier versions of C# that don't have the dynamic keyword (before VS 2010), the type of .Text is object and your original version should compile without issues.

Upvotes: 1

Related Questions