简体   繁体   中英

LINQ search records until parentid = 0

I have a C# List with 3 fields: ID , Name and ParentID . I am binding it to a treeview. Now I am also having a search feature where I want to filter the List and rebind the treeview.

If I search for child-1-1 , my linq should be able to get following records: parent-1 , child-1-1 . So that I have to get records containing my search text and than get the record with ID as ParentID of this. All ParentID s(roots) have ParentID value 0 so I have to keep on getting records until ParentID is 0 .

Example of Data:

ID  Name       ParentID
1   parent-1   0
2   parent-2   0
3   child-1-1  1
4   child-1-2  1
5   child-2-1  2

So my question is how can I get a LINQ expression to get records like I described above?

I mean something like var mydata = from p in this.mylist where... ???

assuming you have List<Node> myList where Node class with properties (Id, ParentId, ...) based on https://stackoverflow.com/a/7063002/1594178 variant for you

static IEnumerable<Node> Parents(this IEnumerable<Node> nodes, int startId)
{
    Node node = nodes.Where(n => n.Id = startId).Single();
    yield return node;
    while (node.ParentId != 0)
    {
        node = nodes.Where(n => n.Id = node.ParentId).Single();
        yield return node;
    }
}

to populate mydata with parents of your child with id = 3 along with that child use

var mydata = mylist.Parents(3)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM