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 null
an element in the XElement constructor content, and it gets ignored. We can therefore move the condition further in:
Func<ErrorType, XElement> recursiveGenerator = null;
recursiveGenerator = (error => new XElement(error.Name,
outputTagsOnly ? null : new XAttribute("Ignore", error.Filter),
error.ChildErrors.Select(recursiveGenerator));
var element = new XElement("ErrorList", ChildErrors.Select(recursiveGenerator));
You can make a decision between values of the same type in a lambda pretty easily:
customer => flag ? customer.Name : customer.Address
You can use an if statement in a lambda with a little more effort:
customer =>
{
if (flag)
return customer.Name
else
return customer.Address
}
Neither of these helps your method greatly.
You could move the "if" statement inside the lambda function safely, if you preferred:
Func<ErrorType, XElement> recursiveGenerator = null;
recursiveGenerator = (error =>
outputTagsOnly
? new XElement(error.Name,
error.ChildErrors.Select(recursiveGenerator));
: new XElement(error.Name, new XAttribute("Ignore", error.Filter),
error.ChildErrors.Select(recursiveGenerator)));
var element = new XElement("ErrorList", ChildErrors.Select(recursiveGenerator));
Other than that, there doesn't seem to be any trivial way to simplify what you've got.
(P.S. When it looks ugly, put some lipstick on that pig by pretty-printing it ;)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With