简体   繁体   中英

How to query Min and Max from XML?

<?xml version="1.0" encoding="utf-8"?>
<Customers>
   <Customer Id="1">
    <Name>rtertr</Name>
    <DOB>2010-12-12T00:00:00</DOB>
    <EMail>werer@test.com</EMail>
  </Customer>
  <Customer Id="2">
    <Name>west</Name>
    <DOB>0001-01-01T00:00:00</DOB>
    <EMail>west@test.com</EMail>
   </Customer> 
  <Customer Id="3">
    <Name>west</Name>
    <DOB>0001-01-01T00:00:00</DOB>
    <EMail>west@test.com</EMail>
   </Customer> 
</Customers>

How to find Min and Max CustomerId from the above sample XML using LinQ to XML? For example for the above sample, Min should be 1 and Max should be 3

var doc = XDocument.Parse(...);

//.ToArray() so we only iterate once
var ids = doc.Root.Elements("Customer").Select(c => (int)c.Attribute("Id")).ToArray();
var minId = ids.Min();
var maxId = ids.Max();

As dtb´s comment says, this will iterate the array twice but only the xml document once. I feel this is a good compromise between readability and performance - at least when its not used in production code. Iterating the int array will be a small factor of the xml document iteration. The best solution is to only iterate the document once and keep track of the values along the way as dtb shows.

You can use the Min and Max extension methods:

var doc = XDocument.Parse("<Customers>...</Customers>");

var minId = doc.Root.Elements().Min(e => (int)e.Attribute("Id"));
var maxId = doc.Root.Elements().Max(e => (int)e.Attribute("Id"));

or the Aggregate extension method (iterating the XML document only once):

var doc = XDocument.Parse("<Customers>...</Customers>");

var result = doc.Root
                .Elements()
                .Select(e => (int)e.Attribute("Id"))
                .Aggregate(
                    Tuple.Create(int.MinValue, int.MaxValue),
                    (t, x) => Tuple.Create(Math.Max(t.Item1, x),
                                           Math.Min(t.Item2, x)));

var maxId = result.Item1;
var minId = result.Item2;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM