locked
what does Descendants keyword does in LINQ ? RRS feed

  • Question

  • User264732274 posted

    what Descendants keyword does ?

    can we omit this ? please write in details with example to understand the usage of Descendants keyword. thanks

    var items = xmldoc.Descendants("whatevernodename")
               .Select(node => node.Value.ToString())
               .Skip(PageTimes100)
               .Take(100)
               .ToList();
    Sunday, July 19, 2015 8:29 AM

Answers

  • User61956409 posted

    Hi sudip_inn,

    what Descendants keyword does ?

    XDocument.Descendants method could returns a collection of the descendant elements for this document or element, in document order. It has two overloads Descendants() and Descendants(XName). For more information, please refer to this link.

    https://msdn.microsoft.com/en-us/library/system.xml.linq.xdocument.descendants(v=vs.110).aspx

    Besides, this sample is for your reference.

    EmployeesInfo.XML

    <?xml version="1.0" encoding="utf-8" ?>
    <Employees>
      <employee id ="1" name="emp1"  designation="Managing Director" company="comp1">emp1</employee>
      <employee id ="2" name="emp2"  designation="Team Leader (S/W)" company="comp2">emp2</employee>
      <employee id ="3" name="emp3"  designation="Managing Director" company="comp1">emp3</employee>
    </Employees>
    

    Web page

    <div>
        <asp:Button ID="btnfind" runat="server" Text="Find Descendant Elements " OnClick="btnfind_Click" />
        <asp:GridView ID="GridView1" runat="server"></asp:GridView>
    </div>
    
    protected void btnfind_Click(object sender, EventArgs e)
    {
        XDocument xmldoc = XDocument.Load(Server.MapPath("Data/EmployeesInfo.XML"));
        var items = xmldoc.Descendants("employee").Select(node => node.Value.ToString()).ToList();
    
        GridView1.DataSource = items;
        GridView1.DataBind();
    }
    

    Best Regards,

    Fei Han



    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, July 20, 2015 4:00 AM