How to use Linq to set counter based attributes
Let's say I have an XML document similar to this
<foo>
<bar id="9" />
<bar id="4" />
<bar id="3" />
</foo>
I would like to use linq to reset the id to 0, 1, 2. What would be the easiest way to do this?
thank
+1
Ryan
source
to share
2 answers
XElement xml = GetXml();
var i = 0;
foreach (var e in xml.Elements("bar"))
e.SetAttributeValue("id", i++);
+3
Will
source
to share
You can do it with linq methods, not foreach, but there is not much for buck:
XElement xml = GetXml();
int updatedElements = xml.Elements("bar")
.Select((x, i) =>
{
x.SetAttributeValue("id", i);
return x;
})
.Count();
Here the Count () method is needed to enumerate the request. Anything the request lists will do.
If using Select as mutator bothers you (as I did), use List (T) .ForEach instead:
XElement xml = GetXml();
xml.Elements("bar")
.Select( (x, i) => new {x, i})
.ToList()
.ForEach(a => a.x.SetAttributeValue("id", a.i));
0
Amy B
source
to share