From e68555e9762a244b2a6440a30dcc9b62233fe522 Mon Sep 17 00:00:00 2001 From: yubaolee Date: Fri, 14 Oct 2016 17:39:21 +0800 Subject: [PATCH] routine update --- Infrastructure/GenericHelpers.cs | 42 ++++++++++++++++++++++++++++++++ Infrastructure/TreeItem.cs | 10 ++++++++ 2 files changed, 52 insertions(+) create mode 100644 Infrastructure/GenericHelpers.cs create mode 100644 Infrastructure/TreeItem.cs diff --git a/Infrastructure/GenericHelpers.cs b/Infrastructure/GenericHelpers.cs new file mode 100644 index 00000000..43182db4 --- /dev/null +++ b/Infrastructure/GenericHelpers.cs @@ -0,0 +1,42 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Infrastructure +{ + /// + /// List转成Tree + /// 李玉宝新增于2016-10-09 19:54:07 + /// + 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, + K rootId = default(K)) + { + foreach (var c in collection.Where(c => parentIdSelector(c).Equals(rootId))) + { + yield return new TreeItem + { + Item = c, + Children = collection.GenerateTree(idSelector, parentIdSelector, idSelector(c)) + }; + } + } + } +} \ No newline at end of file diff --git a/Infrastructure/TreeItem.cs b/Infrastructure/TreeItem.cs new file mode 100644 index 00000000..c4db87bd --- /dev/null +++ b/Infrastructure/TreeItem.cs @@ -0,0 +1,10 @@ +using System.Collections.Generic; + +namespace Infrastructure +{ + public class TreeItem + { + public T Item { get; set; } + public IEnumerable> Children { get; set; } + } +} \ No newline at end of file