开发者

Predicates and Lists

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
    {
     开发者_如何学Python   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 :(


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;
        });


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));


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.


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));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜