0

我有一个通用列表。

此列表的某些元素属于父元素。我从数据库中检索了所有这些元素,我想用它们递归地构建一棵树。

所以,这就是我的想法:

这是我的谓词:

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,???)

我无法弄清楚这将如何工作。我该怎么做这种谓词?

PS:我正在使用VS2005 :(

4

4 回答 4

3

尝试

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

编辑

在.net 2.0 我认为是

root.FindAll(
    delegate(CategoryMapping mapping)
        {
             return mapping.parentId == root.Id;
        });
于 2010-03-16T14:47:20.467 回答
1

您需要指定要传递给的委托FindAll,而不是直接调用函数

(假设rootList<CategoryMapping>

root.childrenElements = root.FindAll(c => FindChildren(root.id, c));
于 2010-03-16T14:47:33.197 回答
1

您应该查看我开始的在C# / .NET 2.0的列表中形成对 Find() 或 FindAll() 的良好谓词委托的线程

它很清楚地回答了你的问题。

于 2010-03-16T18:31:01.020 回答
0

Gregoire 的回答是最好的,因为它:

  1. 不使用 LINQ(提问者使用的是 VS 2005)
  2. 不使用 lambda 表达式(同样,VS 2005)

也就是说,为什么不通过编写一个函数来Predicate 你生成你的东西(稍微)让事情变得更容易:

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

然后,如果您有一个List<CategoryMapping>并且想要查找具有某个parentId属性的所有元素,您可以调用:

root = list[0];
root.childrenElements = list.FindAll(GetIsChildOf(root.id));
于 2010-03-16T18:25:23.740 回答