Click here to Skip to main content
15,886,724 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C#
class Node
{
string Name;
List<Node> NodeList=new List<Node>();
}


Here is my list,so each an every node contains list and name i need to iterate through all the lists to find out match my condition on any of the lists

What I have tried:

I tried foreach but i cant iterate through lists of list,any one give suggesiton.
C#
var element = (from sublist in node.NodeList
from item in sublist.NodeList
where item.Name == "Child 1 P3"
select item).FirstOrDefault();



it will traverse not depth only traversing for two lists,so i confused.
Posted
Updated 25-Feb-21 21:49pm
v2
Comments
Richard MacCutchan 25-Feb-21 8:51am    
Please show the code that you have tried, and indicate where it fails and why.
Fazi_13 25-Feb-21 8:55am    
var element = (from sublist in node.NodeList
from item in sublist.NodeList
where item.Name == "Child 1 P3"
select item).FirstOrDefault();


it will traverse not depth only traversing for two lists,so i confused.
Patrice T 25-Feb-21 9:16am    
Use Improve question to update your question.
So that everyone can pay attention to this information.
PIEBALDconsult 25-Feb-21 9:07am    
Better to make an additional Dictionary to act as an index.
Or maybe you want a Hashset rather than List?
Fazi_13 25-Feb-21 9:10am    
can you explain briefly

If I duplicate what you say you have, it works:
C#
Node node = new Node() { Name = "Head" };
for (int i = 0; i < 5; i++)
    {
    Node subNode = new Node() { Name = $"Child {i} 0" };
    node.NodeList.Add(subNode);

    subNode.NodeList.Add(new Node() { Name = $"Child {i} P1" });
    subNode.NodeList.Add(new Node() { Name = $"Child {i} P2" });
    subNode.NodeList.Add(new Node() { Name = $"Child {i} P3" });
    }
var element = (from sublist in node.NodeList
               from item in sublist.NodeList
               where item.Name == "Child 1 P3"
               select item).FirstOrDefault();
element contains a single node, with the correct name: "Child 1 P3".

I'd start by using the debugger to check exactly what you have in node and all it's subnodes - because if it works with my code, it implies your data is not as you expect.
 
Share this answer
 
Comments
Fazi_13 25-Feb-21 23:40pm    
yes but my problem was if i have Child 1 P3 element in the depth list not in 2nd traverse list it will go depth that time it is failing
OriginalGriff 26-Feb-21 3:27am    
While it is possible to use Linq to recurse, it's horribly messy.

You would be better off not trying to take a "Linq shortcut" but write a quick recursive method to look through a node and it's subnodes for a match instead.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900