开发者

LINQ - Get Max Value of a group of elements

How can I use LINQ to query an XML structure and get a max value for a group of elements that belong to a particular element.

For example, how could I get the maximum age allowed for FullTicket, DayTicket and ChildTicket where the XML structure looks like the below

    <TicketTypes>
      <TicketType Name="FullTicket">
        <AgeBands>
          <AgeBand>
            <Code>Adult1</Code>
            <MinAge>18</MinAge>
            <MaxAge>59</MaxAge>
          </AgeBand>
          <AgeBand>
            <Code>Adult2</Code>
            <MinAge>60</MinAge>
            <MaxAge>64</MaxAge>
          </AgeBand>
          <AgeBand>
            <Code>Adult3</Code>
            <MinAge>65</MinAge>
            <MaxAge>79</MaxAge>
          </AgeBand>
        </AgeBands>
      </TicketType>
      <TicketType Name="DayTicket">
        <AgeBands>
          <AgeBand>
            <Code>Adult2</Code>
            <MinAge>18</MinAge>
            <MaxAge>64</MaxAge>
          </AgeBand>
          <AgeBand>
            <Code>Adult3</Code>
            <MinAge>65</MinAge>
            <MaxAge>89</MaxAge>
          </AgeBand>
        </AgeBands>
      </TicketType>
      <TicketType Name="ChildTicket">
        <AgeBands>
          <AgeBand>
            <Code>Child</Code>
            <MinAge>3</MinAge>
            <MaxAge>17</MaxAge>
          </AgeBand>
          <AgeBand>
            <Code>Infant</Code>
            <MinAge>0</MinAge>
            <MaxAge>2</MaxAge>
          </AgeBand>
        </AgeBands>
      </TicketType>
    </TicketTypes&开发者_如何学Cgt;


You mean you want the highest value of MaxAge? (The fact that there's already "max" here is a bit confusing.) Try something like this:

// Find the FullTicket element
var fullTicket = ticketTypes.Elements("TicketType")
                     .Where(x => (string) x.Attribute("Name") == "FullTicket")
                     .First();

// Find the maximum value of any MaxAge element within FullTicket
var maxFullTicketAge = fullTicket.Descendants("MaxAge")
                                 .Max(x => (int) x);

You can do the same for the other ticket types, or if you're feeling more adventurous you could do something like:

var maxAges = ticketTypes
       .Elements("TicketType")
       .Select(x => new {
                  Name = (string) x.Attribute("Name"),
                  MaxMaxAge = x.Descendants("MaxAge").Max(y => (int) y)
               });


var values = from item in TicketTypes.Descendants("TicketType")
             from agebands in item.Descendants("AgeBands")
             from ageband in agebands.Descendants("AgeBand")
select item.Attribute("Name"), ageBand.MaxAge;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜