| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364 |
- /*-------------------------------------------------------------------------
- * 功能描述:IEnumerableExtensions
- * 作者:xulisong
- * 创建时间: 2019/1/25 11:15:03
- * 版本号:v1.0
- * -------------------------------------------------------------------------*/
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace SAGA.DotNetUtils.Extend
- {
- public static class IEnumerableExtensions
- {
- /*
- * 没有什么是string办不了的
- */
- #region 分组扩展
- /// <summary>
- /// 给指定数据源分组
- /// </summary>
- /// <typeparam name="IN"></typeparam>
- /// <typeparam name="TREE"></typeparam>
- /// <param name="inputSource"></param>
- /// <param name="treeAdd"></param>
- /// <param name="groupConditions"></param>
- /// <returns></returns>
- public static List<TREE> GroupTree<IN, TREE>(this IEnumerable<IN> inputSource, Action<TREE, List<TREE>> treeAdd, List<GroupCondition<IN, TREE>> groupConditions)
- {
- List<TREE> reuslt = new List<TREE>();
- var firstCondition = groupConditions.FirstOrDefault();
- if (firstCondition == null)
- return reuslt;
- var groups = inputSource.GroupBy(firstCondition.GroupKeySelect);
- foreach (var groupItem in groups)
- {
- var tree = firstCondition.GroupSelect(groupItem);
- reuslt.Add(tree);
- if (!firstCondition.GroupContinue(groupItem))
- {
- continue;
- }
- var childNodes = groupItem.ToList().GroupTree(treeAdd, groupConditions.GetRange(1, groupConditions.Count-1));
- treeAdd(tree, childNodes);
- }
- return reuslt;
- }
- #endregion
- }
- /// <summary>
- /// 分组约束类
- /// </summary>
- /// <typeparam name="IN"></typeparam>
- /// <typeparam name="TREE"></typeparam>
- public class GroupCondition<IN, TREE>
- {
- public Func<IN, string> GroupKeySelect { get; set; }
- public Func<IGrouping<string, IN>, bool> GroupContinue { get; set; }
- public Func<IGrouping<string, IN>, TREE> GroupSelect { get; set; }
- }
- }
|