简体   繁体   中英

Help with LINQ to Xml

I posted another post earlier on on how to transform an XmlDocument with XSLT but maybe it is possible to do with LINQ instead.

I have an XmlDocument that looks something like:

<DocumentElement>
  <Customer>
    <CustomerId>2315</CustomerId>
    <VersionNumber>1</VersionNumber>
    <GUID>2E05DE20-02A0-425D-944D-65E5E744FF8A</GUID>
  </Customer>
  <Customer>
    <CustomerId>2316</CustomerId>
    <VersionNumber>2</VersionNumber>
    <GUID>2E05DE20-02A0-425D-944D-65E5E744FF8A</GUID>
  </Customer>
  <Customer>
    <CustomerId>2317</CustomerId>
    <VersionNumber>1</VersionNumber>
    <GUID>9995DE20-02A0-425D-944D-65E5E744FF8A</GUID>
  </Customer>
</DocumentElement>

Can I, with LINQ, extract one customer element for each unique GUID and get the customer with the highest version number?

Ie the new/transformed document will look like:

<DocumentElement>
  <Customer>
    <CustomerId>2316</CustomerId>
    <VersionNumber>2</VersionNumber>
    <GUID>2E05DE20-02A0-425D-944D-65E5E744FF8A</GUID>
  </Customer>
  <Customer>
    <CustomerId>2317</CustomerId>
    <VersionNumber>1</VersionNumber>
    <GUID>9995DE20-02A0-425D-944D-65E5E744FF8A</GUID>
  </Customer>
</DocumentElement>

Thanks in advance.

Update:

So I should do (if I understand you correctly?):

    XDocument xdoc = new XDocument();
    using (StringWriter sw = new StringWriter())
    {
        // Converts the datatable to XML                             
        dt.WriteXml(sw);
        xdoc = XDocument.Parse(sw.ToString());
    }

        var query = xdoc.Root
            .Elements("Customer")
            .GroupBy(x => x.Element("GUID").Value)
            .Select(g => g.OrderByNumberDescending(x =>(int)x.Element("VersionNumber"))
                          .First());

I still get the error on GroupBy though, or am I doing something else wrong here?

Absolutely:

var query = parent
    .Elements("Customer")
    .GroupBy(x => x.Element("GUID").Value)
    .Select(g => g.OrderByNumberDescending(x => (int) x.Element("VersionNumber"))
                  .First());

Or using MoreLINQ :

var query = parent
     .Elements("Customer")
     .GroupBy(x => x.Element("GUID").Value)
     .Select(g => g.MaxBy(x => (int) x.Element("VersionNumber")));

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