I am trying to create save a data structure as xml like so:
return new XElement ( "EffectFile",
new XElement ( "Effects", this.Effects.Select ( e => new XElement ( "Effect", e.EffectType ) ) )
).ToString ( );
which creates something like this:
开发者_高级运维<EffectFile>
<Effects>
<Effect>Blur</Effect>
<Effect>Sharpen</Effect>
<Effect>Median</Effect>
</Effects>
</EffectFile>
But I also want to have a condition that if an effect has opacity, I want to save that too within the effect.
I just can't workout how to nest that condition inside the lambda expression to create a nested XElement.
EDIT: So for Opacity, let's say it's something like this:
if (e.Opacity != null) new xElement("Opacity", e.Opacity)
It is better for you to store your file like that:
<EffectFile>
<Effects>
<Effect>
<EffectType>Blur</EffectType>
<Opacity>100</Opacity>
</Effect>
</Effects>
</EffectFile>
_
return new XElement("EffectFile",
new XElement("Effects", this.Effects.Select(e => new XElement("Effect", new XElement("EffectType", e.EffectType), e.Opacity != null ? new XElement("Opacity", e.Opacity) : null)))
).ToString();
Assuming Opacity
is a float
instance property on your class, you could combine the ternary operator (?:) with the Concat
extension method.
return new XElement("EffectFile",
new XElement("Effects",
this.Effects
.Select(e => new XElement("Effect", e.EffectType))
.Concat(this.Opacity > 0.0f
? new[] { new XElement("Opacity", this.Opacity) }
: Enumerable.Empty<XElement>()
)
)
)
.ToString();
Translation of my additions:
If opacity is greater than zero, make a new list of size 1 (with an Opacity element), and append that to the effects list. If opacity is less than or equal to zero, make a new list of size zero, and append that to the effects list (basically a no-op, as far as the list goes).
Your output file will look like the one you specified in your question if the opacity is <= 0, and should look like this if it is > 0:
<EffectFile>
<Effects>
<Effect>Blur</Effect>
<Effect>Sharpen</Effect>
<Effect>Median</Effect>
<Opacity>0.75</Opacity>
</Effects>
</EffectFile>
Edit:
To match your new specifications, simply change this.Opacity > 0.0f
to this.Opacity != null
, and make sure you have the appropriate ToString
method defined for Opacity
. The resulting XML will end up looking more-or-less the same.
精彩评论