0

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 :(

George Silva
  • 3,454
  • 10
  • 39
  • 64
  • 3
    @George: In case you didn't know, you can just `return catMapping.parentId == parentId`, you don't need the if/else statement. – Binary Worrier Mar 16 '10 at 17:08

4 Answers4

3

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;
        });
balexandre
  • 73,608
  • 45
  • 233
  • 342
Gregoire
  • 24,219
  • 6
  • 46
  • 73
1

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
  • 45,220
  • 19
  • 132
  • 189
  • George is using VS 2005, so a lambda expression won't work. He needs to use the `delegate` syntax. – Dan Tao Mar 16 '10 at 18:26
1

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.

Community
  • 1
  • 1
Pretzel
  • 8,141
  • 16
  • 59
  • 84
0

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
  • 125,917
  • 54
  • 300
  • 447
  • 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 Silva Mar 16 '10 at 18:48