Optimizing C# code (function) RRS feed

  • Question

  • Hi Guys,

    I have a code to build a tree in Windows Form application, I am getting the result what I want but it is taking a long time since it is reading the xml and there are two for loops.

    Can someone please advise optimizing ideas to make this run faster or probably a better way to create a tree structure in WF.

    i would appreciate any help.


    XmlNode MainNode = doc.DocumentElement.SelectSingleNode("Main");
    			foreach (XmlNode node in doc.DocumentElement.SelectNodes("Country/city")) 
                    int id = node.GetID("id", -1);
                    string filter = string.Format("{0}={1}", NodeID, id);
                    DataRow[] rows = Table1.Select(filter);
                    string city = rows[0][DB.("city")].ToString();
                    filter = string.Format("{0}={1}", DB.("CityID") ,id);
                    foreach (DataRow cityRow in Table2.Select(filter)) 
                        int localID = cityRow[("LocalID")]];
                        AddTreeItem(city, localID, MainNode);

    Tuesday, August 20, 2019 9:51 PM

All replies

  • Try surround your code with the following code block to suspend tree redraw while you're still adding data.

        // your codes goes here...

    If your code runs on other thread, you may need some way to pass your current "form" object to this thread. (I assume it's possible becaue your AddTreeItem() should have some way to refer to the TreeView control itself)

    Wednesday, August 21, 2019 1:41 AM
  • Hi SA260884,

    Thank you for posting here.

    If you want to optimize this code, I suggest that you could use XDocument Class to do it.

    The following link describes that XDocument is faster than XmlDocument.

    Performance: XDocument versus XmlDocument

    If you want to know how to do this in your code, please provide the related xml and AddTreeItem method.

    Best Regards,


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact

    Wednesday, August 21, 2019 5:34 AM
  • If Node ID is unique in Table1 and City ID is unique in Table2, the maybe define the corresponding Primary Keys using PrimaryKey property of the tables.

    Accessing a cell using expressions like cityRow["LocalID"] can be replaced with cityRow[c] or cityRow[i], where c is DataColumn and i is the index (i.e. c.Ordinal), which can be obtained and stored before your loops.

    • Edited by Viorel_MVP Wednesday, August 21, 2019 7:15 AM
    Wednesday, August 21, 2019 7:14 AM