using System;
using System.Collections.Generic;
using System.Linq;
namespace CommonTool
{
///
/// List转成Tree
///
public static class GenericHelpers
{
///
/// Generates tree of items from item list
///
///
/// Type of item in collection
/// Type of parent_id
///
/// Collection of items
/// Function extracting item's id
/// Function extracting item's parent_id
/// Root element id
///
/// Tree of items
public static IEnumerable> GenerateTree(
this IEnumerable collection,
Func idSelector,
Func parentIdSelector,
TK rootId = default(TK))
{
var enumerable = collection as T[] ?? collection.ToArray();
foreach (var c in enumerable.Where(c => parentIdSelector(c).Equals(rootId)))
{
yield return new TreeItem
{
Item = c,
Children = enumerable.GenerateTree(idSelector, parentIdSelector, idSelector(c))
};
}
}
}
}