Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursive call - Action lambda

What am I doing wrong here? How can I execute my action?

var recurse = new Action<IItem, Int32>((item, depth) => {     if (item.Items.Count() > 0) recurse(item, depth + 1); // red squiggly here      // ... }); 

I'm getting a red squiggly when calling recurse saying "method, delegate or event expected".


Update

I've accepted Homam's answer. I'd just like to add/share another syntax for the same... But which I find a bit easier on the eyes...

Action<IEnumerable<Item>> Recurse = null;  Recurse = item => {     if (item.Items != null) Recurse(item.Items);      // ... }; 
like image 920
cllpse Avatar asked Oct 26 '10 14:10

cllpse


People also ask

Can lambda functions be called recursively?

A recursive lambda expression is the process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. Using a recursive algorithm, certain problems can be solved quite easily.


1 Answers

Just define the delegate Action and assign null to it before calling it recursively.

Action<IItem, Int32> recurse = null; 

Then

recurse = new Action<IItem, Int32>((item, depth ) => {     if (item.Items.Count() > 0) recurse(item, depth + 1); // red squiggly here     // ... }); 

Good luck!

like image 195
Homam Avatar answered Oct 15 '22 12:10

Homam