Looping and looping… how about some declarative code

I was given the task to solve an issue with our Video streaming solution (written in C#) where search strings were not returning the correct results. What fun.

So after an hour or so I realized the search loop was not processing the XML file returned. In fact once windows search returned the file, a simple string match was done on the innerText property of the XmlNode object which gave an concatenated string, causing the search to fail.

So my solution was easy, once the XML document was loaded, search for section elements, then get all the descendant elements below each section and then remove any empty strings for those nodes and then traverse the list until I have a match.

So this is what I came up with:

Okay, bug fixed and I can go home.

However all the looping and remembering indexes and then jumping out of loops did not feel right with me.

So as I described above exactly what I needed but I did not have any break, indexes, checking for empty strings (although I did say remove empty values) etc in my explanation of my solution.

So why not make my code more declarative. I have been dabbling with some Javascript functional code which I will blog about later but this is what I have once I switched to using LINQ.

The first line gives me all of the nodes that are not empty. Now the second section of the code loops through the list to find the match and then breaks out.

By treating the problem with a functional approach I can read pretty much what the first line does. The rest of the code is pretty straight forward.

However, after looking at the actual usage of this code I found that there was no need to record the index. So now my code is:

That is pretty much it.

One of the downsides is debugging as LINQ is not easy to debug at all (although Visual Studio 2015 has debugging built in). However breaking up the statement into variables makes it easier.