Search code examples
c#xmllistlinqgroup-by

How to get highest value from xml element in C#?


I need to get the highest <WbDrillPermitNo> ie 692753 from <WBWellIdSegment>.I wrote the code using linq as below but it's returning both <WBWellIdSegment> as result. Please help me get the maximum value.

 XDocument xml1 = XDocument.Load(File.FullName);

     List<XElement> segLists = xml1.Descendants("WBWellIdSegmentList").Descendants("WBWellIdSegment").Elements("WbDrillPermitNo").ToList();
     
     var result = segLists.GroupBy(i => i.Elements("WbDrillPermitNo"),
                  (i, group) => group.Single(x => x.Element("WbDrillPermitNo").Value == group.Max(y => 
                  y.Element("WbDrillPermitNo").Value)));

xml file

 <WBWellIdSegmentList>
          <WBWellIdSegment>     
            <WbOilLseNumber>07337</WbOilLseNumber>
            <WbOilWellNumber>1486W</WbOilWellNumber>
            <WbDrillPermitNo>370746</WbDrillPermitNo>       
          </WBWellIdSegment>
          <WBWellIdSegment>
            <WbOilLseNumber>07337</WbOilLseNumber>
            <WbOilWellNumber>1486</WbOilWellNumber>
            <WbDrillPermitNo>692753</WbDrillPermitNo>        
          </WBWellIdSegment>
    </WBWellIdSegmentList>

Solution

  • To return max value (assume that the value is of type integer)

    wellBore.Descendants("WbDrillPermitNo").Select(e => int.Parse(e.Value)).Max();
    

    To return element <WBWellIdSegment> with max value from <WbDrillPermitNo> you can use Aggregate method

    var segmentWithMaxNumber = wellBore.Descendants("WBWellIdSegment")
       .Select(e => (Element: e, Number: int.Parse(e.Element("WbDrillPermitNo").Value)))
       .Aggregate((max, e) => e.Number > max.Number ? e : max, max => max.Element);