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(u => { var selector = parentIdSelector(u); return (rootId == null && selector == null) || (rootId != null &&rootId.Equals(selector)); })) { yield return new TreeItem { Item = c, Children = collection.GenerateTree(idSelector, parentIdSelector, idSelector(c)) }; } } /// /// 把数组转为逗号连接的字符串 /// /// /// /// public static string ArrayToString(dynamic data, string Str) { string resStr = Str; foreach (var item in data) { if (resStr != "") { resStr += ","; } if (item is string) { resStr += item; } else { resStr += item.Value; } } return resStr; } } }