Get List<Guid> from object C#

I have function GetChildren, which returns all the child nodes, in a structure as they need to be in treeview.

 public static object GetChildrenNodes(IEnumerable<NodeDto> aNodes, Guid aNodeGuid)
    {
        var childrens = from childrenNode in aNodes
                        where (childrenNode.NodeParentGuid == aNodeGuid)
                        select new
                        {
                            id = childrenNode.NodeGuid,
                            text = childrenNode.Label,
                            nodes = (aNodes.Count(x => x.NodeParentGuid == childrenNode.NodeGuid) > 0) ? GetChildrenNodes(aNodes, childrenNode.NodeGuid) : null
                        };

        return childrens;
    }

This function must remain as is, because TreeView requires that kind of object to build itself.

I would like to use the same function to get the guids of nodes to delete, so i have:

 object nodesList = GetChildrenNodes(nodeList, aNodeGuid);

The thing is i want to get List<Guid> guids from "id"s of object nodesList, so i please for your help.

Jon Skeet
people
quotationmark

I would avoid using the same method. You've got two different requirements:

  • Build a collection of anonymous types for use in the UI
  • Build a list of GUIDs for children of the given node ID

(I'm assuming you only want direct children, rather than all descendants? It's not clear.)

They may have the same filter, but that's about all. I'd suggest factoring out the common part (the filtering) and then having two different methods that call it:

private static IEnumerable<NodeDto> FindChildren(
    IEnumerable<NodeDto> allNodes, Guid parentId) =>
    allNodes.Where(node => node.NodeParentGuid == parentId);

public static object GetChildrenNodes(IEnumerable<NodeDto> allNodes, Guid parentId) =>
    FindChildren(allNodes, parentId).Select(node =>
    {
        id = childrenNode.NodeGuid,
        text = childrenNode.Label,
        nodes = allNodes.Any(x => x.NodeParentGuid == node.NodeGuid) 
            ? GetChildrenNodes(allNodes, node.NodeGuid) : null
    });

public static List<Guid> FindChildIds(IEnumerable<NodeDto> allNodes, Guid parentId) =>
    FindChildren(allNodes, parentId).Select(node => node.NodeGuid).ToList();

people

See more on this question at Stackoverflow