You must Sign In to post a response.
  • Category: LINQ

    Find max value of field in xml using Linq

    Hi,

    I want to find the maximum value of a particular field from XML file.

    following is my XML file

    <?xml version="1.0" encoding="utf-8"?>
    <FeeGroups>
    <FeeGroup>
    <FeegId>100</FeegId>
    <Fgname>sss</Fgname>
    <FgDetail>dgdgdgdg</FgDetail> />
    </FeeGroup>
    <FeeGroup>
    <FeegId>101</FeegId>
    <Fgname>sss1</Fgname>
    <FgDetail>rtrtrt</FgDetail>
    </FeeGroup>
    <FeeGroup>
    <FeegId>102</FeegId>
    <Fgname>sss2</Fgname>
    <FgDetail>klklkl</FgDetail>
    </FeeGroup>
    <FeeGroup>
    <FeegId>103</FeegId>
    <Fgname>sss3</Fgname>
    <FgDetail>mnmnmn</FgDetail>
    </FeeGroup>

    </FeeGroups>

    my requirement is to fetch the maximum value of FeegId from the above xml


    Regards

    Baiju
  • #763546
    Following are some tips to do your task

    XElement element = XElement.Load("Your.xml");
    int max =
    element.Elements("FeeGroup").Max(l => int.Parse(l.Value));

    By Nathan
    Direction is important than speed

  • #763551
    Use ToArray() method to get all inner text in array with specific element, check following snippet
    var textArray = topElement.Elements("FeegId")
    .Select(x => x.Value)
    .ToArray();
    use Max() method of maximum from array, see snippet
    string szMax = array1.Max());

    Thanks
    Koolprasd2003
    Editor, DotNetSpider MVM
    Microsoft MVP 2014 [ASP.NET/IIS]

  • #766188
    Hi
    You can use following code

    XElement ex = XElement.Load(@"C:\Umesh\Demo\DotnetSpidder\R_D\R_D\input.xml");
    var maxval = (from x in ex.Elements("FeeGroup").Elements("FeegId")
    select new
    {
    x.Value
    }).ToList().OrderByDescending(y => y.Value).ToList()[0];


    Console.WriteLine(maxval.Value);

    //-- Hope it will help you !!!!
    Thanks
    Umesh Bhosale


  • Sign In to post your comments