views:

97

answers:

4

Hello guys,

I have a generic list.

Some elements of this list belong to a parent element. I retrieved all these elements from a database and i want to recursively build a tree with them.

So, here's what i'm thinking:

Here is my predicate:

public static bool FindChildren(Int32 parentId,CategoryMapping catMapping)
{
    if (catMapping.parentId == parentId)
    {
        return true;
    }
    else
    {
        return false;
    }
}

root = list[0];
root.childrenElements = root.FindAll(FindChildren(root.id,???)

I can't figure out how this would work. How can i do this kind of predicate?

PS: I'm using VS2005 :(

+2  A: 

Try

root.childrenElements = 
    root
       .Where( i => i.parentId == yourCatMapping.parentId)
       .ToArray();

EDIT

In .net 2.0 I think it is

root.FindAll(
    delegate(CategoryMapping mapping)
        {
             return mapping.parentId == root.Id;
        });
Gregoire
Asker is on .net 2.0, and therefore doesn't have linq
Binary Worrier
@Binary Worrier: the PS of the question is recent ;)
Gregoire
Gotcha, my bad :)
Binary Worrier
+1  A: 

You need to specify a delegate to pass to FindAll, rather than a direct function call

(assuming root is List<CategoryMapping>)

root.childrenElements = root.FindAll(c => FindChildren(root.id, c));
thecoop
George is using VS 2005, so a lambda expression won't work. He needs to use the `delegate` syntax.
Dan Tao
A: 

Gregoire's answer is the best, because it:

  1. Doesn't use LINQ (the asker is using VS 2005)
  2. Doesn't use a lambda expression (again, VS 2005)

That said, why not make things (slightly) easier for yourself by writing a function to generate your Predicate for you:

public static Predicate<CategoryMapping> GetIsChildOf(int parentId) {
    return delegate(CategoryMapping cm) {
        return cm.parentId == parentId;
    };
}

Then if you have a List<CategoryMapping> and you want to find all elements with a certain parentId property, you can just call:

root = list[0];
root.childrenElements = list.FindAll(GetIsChildOf(root.id));
Dan Tao
great post dan. it cleared some things for me. Thanks all of you! SO is great. Thanks a lot guys, i was going crazy on this.
George
+1  A: 

You should check out this thread that I started on Forming good predicate delegates to Find() or FindAll() in a List for C# / .NET 2.0

It answers your question pretty clearly.

Pretzel
thanks for pointing it out.
George