IEnumerableExtensions.cs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /*-------------------------------------------------------------------------
  2. * 功能描述:IEnumerableExtensions
  3. * 作者:xulisong
  4. * 创建时间: 2019/1/25 11:15:03
  5. * 版本号:v1.0
  6. * -------------------------------------------------------------------------*/
  7. using System;
  8. using System.Collections.Generic;
  9. using System.Linq;
  10. using System.Text;
  11. using System.Threading.Tasks;
  12. namespace SAGA.DotNetUtils.Extend
  13. {
  14. public static class IEnumerableExtensions
  15. {
  16. /*
  17. * 没有什么是string办不了的
  18. */
  19. #region 分组扩展
  20. /// <summary>
  21. /// 给指定数据源分组
  22. /// </summary>
  23. /// <typeparam name="IN"></typeparam>
  24. /// <typeparam name="TREE"></typeparam>
  25. /// <param name="inputSource"></param>
  26. /// <param name="treeAdd"></param>
  27. /// <param name="groupConditions"></param>
  28. /// <returns></returns>
  29. public static List<TREE> GroupTree<IN, TREE>(this IEnumerable<IN> inputSource, Action<TREE, List<TREE>> treeAdd, List<GroupCondition<IN, TREE>> groupConditions)
  30. {
  31. List<TREE> reuslt = new List<TREE>();
  32. var firstCondition = groupConditions.FirstOrDefault();
  33. if (firstCondition == null)
  34. return reuslt;
  35. var groups = inputSource.GroupBy(firstCondition.GroupKeySelect);
  36. foreach (var groupItem in groups)
  37. {
  38. var tree = firstCondition.GroupSelect(groupItem);
  39. reuslt.Add(tree);
  40. if (!firstCondition.GroupContinue(groupItem))
  41. {
  42. continue;
  43. }
  44. var childNodes = groupItem.ToList().GroupTree(treeAdd, groupConditions.GetRange(1, groupConditions.Count-1));
  45. treeAdd(tree, childNodes);
  46. }
  47. return reuslt;
  48. }
  49. #endregion
  50. }
  51. /// <summary>
  52. /// 分组约束类
  53. /// </summary>
  54. /// <typeparam name="IN"></typeparam>
  55. /// <typeparam name="TREE"></typeparam>
  56. public class GroupCondition<IN, TREE>
  57. {
  58. public Func<IN, string> GroupKeySelect { get; set; }
  59. public Func<IGrouping<string, IN>, bool> GroupContinue { get; set; }
  60. public Func<IGrouping<string, IN>, TREE> GroupSelect { get; set; }
  61. }
  62. }