
Code
public static class CollectionExtensions


{
public static ICollection<T> BuildTree<T, TKey>(
this ICollection<T> collection,
Func<T, TKey> getKey,
Func<T, TKey> getParentKey,
Func<T, ICollection<T>> getChildren,
TKey topestParentKey)

{
for (int i = 0; i < collection.Count; i++)

{
T element = collection.ElementAt(i);
TKey elementKey = getKey(element);

foreach (var member in collection)

{
if (object.Equals(getParentKey(member), elementKey))

{
getChildren(element).Add(member);
}
}
}

for (int i = 0; i < collection.Count; i++)

{
T element = collection.ElementAt(i);
TKey elementKey = getKey(element);

if (!object.Equals(getParentKey(element), topestParentKey))

{
collection.Remove(element);
--i;
}
}

return collection;
}
}

Sample
static class Program


{
static void Main(string[] args)

{
List<Node> nodes = BuildNodes();
Console.WriteLine("Total: {0}", nodes.Count);

var result = nodes.BuildTree(
node => node.ID,
node => node.Parent == null ? null : node.Parent.ID,
node => node.Children,
null)
.OrderBy(node => node.ID);

int total = 0;
Write(result, ref total);
Console.WriteLine("Total: {0}", total);

Console.Write("Press any key to exit
");
Console.ReadKey(true);
}

static void Write(IEnumerable<Node> nodes, ref int total)

{
foreach (var node in nodes)

{
Console.WriteLine(node.ID);
++total;

Write(node.Children, ref total);
}
}

static List<Node> BuildNodes()

{
Random random = new Random();
List<Node> allNodes = new List<Node>();

for (int i = 1; i <= 3; i++)

{
Node first = new Node()

{
ID = string.Format("First {0}", i),
Order = random.Next(1, 1000)
};
allNodes.Add(first);

for (int j = 1; j <= 3; j++)

{
Node second = new Node()

{
ID = string.Format("Second {0} {1}", i, j),
Order = random.Next(1, 1000),
Parent = first
};
allNodes.Add(second);

for (int k = 1; k <= 3; k++)

{
Node third = new Node()

{
ID = string.Format("Third {0} {1} {2}", i, j, k),
Order = random.Next(1, 1000),
Parent = second
};
allNodes.Add(third);
}
}
}

return allNodes.OrderBy(node => node.Order).ToList();
}
}

class Node


{
public string ID;
public Node Parent;
public int Order;
public readonly List<Node> Children = new List<Node>();
}
posted @
2009-08-19 00:52
周巍
阅读(
215)
评论()
收藏
举报