This may be quite simple but I’m rather new to Lambda’s so bear with me.
I have a function that uses a Lambda function to recurse.
The main function receives a bool telling it to include certain information or not within the lambda.
The function is designed to write out a custom class to XML – I think the code is pretty self explanitory.
At the moment I have overcome the problem using a simple if statement, but it feels ugly so wondered if anyone knew a better way?
private XElement ErrorListToXml(ErrorList el, bool outputTagsOnly)
{
// Need to declare in advance to call within the lambda.
Func<ErrorType, XElement> recursiveGenerator = null;
if (outputTagsOnly)
recursiveGenerator = error => new XElement
(error.Name,
error.ChildErrors.Select(recursiveGenerator));
else
recursiveGenerator = error => new XElement
(error.Name,
new XAttribute("Ignore", error.Filter),
error.ChildErrors.Select(recursiveGenerator));
var element = new XElement
("ErrorList",
ChildErrors.Select(recursiveGenerator));
Console.WriteLine(element);
return element;
}
mquander’s solution can be improved slightly to reduce duplication. You can use the fact that you can pass in
nullan element in the XElement constructor content, and it gets ignored. We can therefore move the condition further in: