Get max

  • Thread starter Thread starter shapper
  • Start date Start date
S

shapper

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
 
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! |
*******************************************
 
shapper said:
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

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
);
 
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
      );

Thank you Goran and Gregory.
 
Back
Top