Extensions.cs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Diagnostics;
  6. #pragma warning disable
  7. namespace Svg
  8. {
  9. public static class Extensions
  10. {
  11. public static IEnumerable<SvgElement> Descendants<T>(this IEnumerable<T> source) where T : SvgElement
  12. {
  13. if (source == null) throw new ArgumentNullException("source");
  14. return GetDescendants<T>(source, false);
  15. }
  16. private static IEnumerable<SvgElement> GetAncestors<T>(IEnumerable<T> source, bool self) where T : SvgElement
  17. {
  18. foreach (var start in source)
  19. {
  20. if (start != null)
  21. {
  22. for (var elem = (self ? start : start.Parent) as SvgElement; elem != null; elem = (elem.Parent as SvgElement))
  23. {
  24. yield return elem;
  25. }
  26. }
  27. }
  28. yield break;
  29. }
  30. private static IEnumerable<SvgElement> GetDescendants<T>(IEnumerable<T> source, bool self) where T : SvgElement
  31. {
  32. var positons = new Stack<int>();
  33. int currPos;
  34. SvgElement currParent;
  35. foreach (var start in source)
  36. {
  37. if (start != null)
  38. {
  39. if (self) yield return start;
  40. positons.Push(0);
  41. currParent = start;
  42. while (positons.Count > 0)
  43. {
  44. currPos = positons.Pop();
  45. if (currPos < currParent.Children.Count)
  46. {
  47. yield return currParent.Children[currPos];
  48. currParent = currParent.Children[currPos];
  49. positons.Push(currPos + 1);
  50. positons.Push(0);
  51. }
  52. else
  53. {
  54. currParent = currParent.Parent;
  55. }
  56. }
  57. }
  58. }
  59. yield break;
  60. }
  61. }
  62. }
  63. #pragma warning restore