Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Get max

0 views
Skip to first unread message

shapper

unread,
Nov 6, 2009, 7:46:33 AM11/6/09
to
Hello,

I am trying to get the maximum Id value from all Asset nodes in a XML
file:
private XDocument _assets;
// ...
Int32 id = _assets.Root.Elements("Asset").Max(s => Int32.Parse
(s.Element("Id").Value));

I am not sure if this is the best way to do it.
And how can I define a default value 1 if there are no nodes Asset in
the file?

Thanks,
Miguel

Gregory A. Beamer

unread,
Nov 6, 2009, 9:02:31 AM11/6/09
to
shapper <mdm...@gmail.com> wrote in news:6518c356-31d6-4ac6-ac24-
dee953...@a31g2000yqn.googlegroups.com:

> And how can I define a default value 1 if there are no nodes Asset in
> the file?

First, set up an XQuery test for Asset nodes. if none, set the id to 1.
If there are some, then run your max query. Without spending time
playing, I am not sure if that is the most "efficient" query you can
have.

Peace and Grace,

--
Vote for Miranda's Christmas Story
http://tinyurl.com/mirandabelieve

Twitter: @gbworld
Blog: http://gregorybeamer.spaces.live.com

*******************************************
| Think outside the box! |
*******************************************

Göran Andersson

unread,
Nov 6, 2009, 9:45:14 AM11/6/09
to

That's pretty efficient. Unless you have some extra information, like
that the elements are sorted by id, then there is no method that is much
better as you have to loop though all the nodes to get the max value.

The Max method throws an exception if there are no items, so you can use
the Aggregate method instead to get a default value:

int? max =
_assets
.Root
.Elements("Asset")
.Select(s => Int32.Parse(s.Element("Id").Value))
.Aggregate(
(int?)null,
(a, i) => !a.HasValue || a.Value < i ? i : a
);

--
G�ran Andersson
_____
http://www.guffa.com

shapper

unread,
Nov 7, 2009, 10:20:38 AM11/7/09
to
> Göran Andersson
> _____http://www.guffa.com

Thank you Goran and Gregory.

0 new messages