Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any chances to imitate times() Ruby method in C#?

Every time I need to do something N times inside an algorithm using C# I write this code

for (int i = 0; i < N; i++) {     ... } 

Studying Ruby I have learned about method times() which can be used with the same semantics like this

N.times do     ... end 

Code fragment in C# looks more complex and we should declare useless variable i.

I tried to write extension method which returns IEnumerable, but I am not satisfied with the result because again I have to declare a cycle variable i.

public static class IntExtender {     public static IEnumerable Times(this int times)     {         for (int i = 0; i < times; i++)             yield return true;     } }  ...  foreach (var i in 5.Times()) {     ... } 

Is it possible using some new C# 3.0 language features to make N times cycle more elegant?

like image 547
Alexander Prokofyev Avatar asked Oct 07 '08 08:10

Alexander Prokofyev


2 Answers

A slightly briefer version of cvk's answer:

public static class Extensions {     public static void Times(this int count, Action action)     {         for (int i=0; i < count; i++)         {              action();         }     }      public static void Times(this int count, Action<int> action)     {         for (int i=0; i < count; i++)         {              action(i);         }     } } 

Use:

5.Times(() => Console.WriteLine("Hi")); 5.Times(i => Console.WriteLine("Index: {0}", i)); 
like image 56
Jon Skeet Avatar answered Sep 30 '22 21:09

Jon Skeet


It is indeed possible with C# 3.0:

public interface ILoopIterator {     void Do(Action action);     void Do(Action<int> action); }  private class LoopIterator : ILoopIterator {     private readonly int _start, _end;      public LoopIterator(int count)     {         _start = 0;         _end = count - 1;     }      public LoopIterator(int start, int end)     {         _start = start;         _end = end;     }        public void Do(Action action)     {         for (int i = _start; i <= _end; i++)         {             action();         }     }      public void Do(Action<int> action)     {         for (int i = _start; i <= _end; i++)         {             action(i);         }     } }  public static ILoopIterator Times(this int count) {     return new LoopIterator(count); } 

Usage:

int sum = 0; 5.Times().Do( i =>      sum += i ); 

Shamelessly stolen from http://grabbagoft.blogspot.com/2007/10/ruby-style-loops-in-c-30.html

like image 21
cvk Avatar answered Sep 30 '22 20:09

cvk