August 26, 2015

Recursion In LINQ

A method which called itself is called "Recursive". These methods are extensively used in daily programming practices. We use it to solve the complex problems or puzzles we face in code. Using recursion add needless complication in other programs.

Before jump into the LINQ world, let me tell you the method definition and implementation. The method should contain the reference variable parameter. It checks a condition near the top of its method body, as many recursive algorithms do.

So if you see the same method signature repeated many times in the call stack, you have a recursive method.

Back to topic, so how the we can acheive the recursion in LINQ query. It is good here to follow the example and write a LINQ query according to it.

Suppose I have list Candy. And each candy have different flavors while some flavor may extend to their child flavors. We need to calculate the 'Total Count' of candy flavors. How do we acheive this?

Diagram of this case is like this tree:


Candy --> Flavor1
Candy --> Flavor2 --> SubFlavor1 --> One, Two
Candy --> Flavor2 --> 
Candy --> Flavor2 --> SubFlavor1 --> Three --> Four, Six

SOLUTION:

We will use 'SelectMany' in order to calculate the 'Total Flavors' count. When we use 'SelectMany', it collapses many elements into a single collection. The code logic will be:


var flavorCount = candyList.SelectMany(sm => sm.Flavors).Count(); // C#

Dim flavorCount = candyList.SelectMany(Function(sm) sm.Flavors).Count() ' VB.NET

You see that!!! this is very simple in LINQ in order to count the 'Total Flavor'. Here I used 'SelectMany' in order to get the count. 

Let me know if have any queries left.

Cheers

No comments:

Post a Comment