How to use Linq to set counter based attributes
2 answers
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
source to share