SingleLinkedNode.cs 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the Apache 2.0 License.
  3. // See the LICENSE file in the project root for more information.
  4. using System.Collections.Generic;
  5. using System.Diagnostics;
  6. namespace System.Linq
  7. {
  8. internal sealed class SingleLinkedNode<TSource>
  9. {
  10. public SingleLinkedNode(TSource first, TSource second)
  11. {
  12. Linked = new SingleLinkedNode<TSource>(first);
  13. Item = second;
  14. Count = 2;
  15. }
  16. public SingleLinkedNode(TSource item)
  17. {
  18. Item = item;
  19. Count = 1;
  20. }
  21. private SingleLinkedNode(SingleLinkedNode<TSource> linked, TSource item)
  22. {
  23. Debug.Assert(linked != null);
  24. Linked = linked;
  25. Item = item;
  26. Count = linked.Count + 1;
  27. }
  28. public TSource Item { get; }
  29. public SingleLinkedNode<TSource> Linked { get; }
  30. public int Count { get; }
  31. public SingleLinkedNode<TSource> Add(TSource item) => new SingleLinkedNode<TSource>(this, item);
  32. public IEnumerator<TSource> GetEnumerator()
  33. {
  34. var array = new TSource[Count];
  35. var index = Count;
  36. for (var n = this; n != null; n = n.Linked)
  37. {
  38. --index;
  39. array[index] = n.Item;
  40. }
  41. Debug.Assert(index == 0);
  42. return ((IEnumerable<TSource>)array).GetEnumerator();
  43. }
  44. }
  45. }