code_junkie

What's the best way to write [0..100] in C#?

Nov 11th, 2011
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.33 KB | None | 0 0
  1. IEnumerable<int> EnumerateIntegerRange(int from, int to)
  2. {
  3. for (int i = from; i <= to; i++)
  4. {
  5. yield return i;
  6. }
  7. }
  8.  
  9. public static IEnumerable<int> To(this int start, int end)
  10. {
  11. return start.To(end, i => i + 1);
  12. }
  13.  
  14. public static IEnumerable<int> To(this int start, int end, Func<int, int> next)
  15. {
  16. int current = start;
  17. while (current < end)
  18. {
  19. yield return current;
  20. current = next(current);
  21. }
  22. }
  23.  
  24. 1.To(100)
  25.  
  26. class Range<T> where T: IComparable<T>
  27. {
  28. public T From { get; set; }
  29. public T To { get; set; }
  30.  
  31. public Range(T from, T to) { this.From = from; this.To = to; }
  32.  
  33. public IEnumerable<T> Enumerate(Func<T, T> next)
  34. {
  35. for (T t = this.From; t.CompareTo(this.To) < 0; t = next(t))
  36. {
  37. yield return t;
  38. }
  39. }
  40.  
  41. static void Example()
  42. {
  43. new Range<int> (0, 100).Enumerate(i => i+1)
  44. }
  45. }
  46.  
  47. class EnumerableRange<T> : Range<T>, IEnumerable<T>
  48. where T : IComparable<T>
  49. {
  50. readonly Func<T, T> _next;
  51. public EnumerableRange(T from, T to, Func<T, T> next)
  52. : base(from, to)
  53. {
  54. this._next = next;
  55. }
  56.  
  57. public IEnumerator<T> GetEnumerator()
  58. {
  59. return Enumerate(this._next).GetEnumerator();
  60. }
  61.  
  62. IEnumerator IEnumerable.GetEnumerator()
  63. {
  64. return this.GetEnumerator();
  65. }
  66. }
Add Comment
Please, Sign In to add comment