Skip to content

Instantly share code, notes, and snippets.

@iwamoto-takaaki
Last active December 1, 2018 17:15
Show Gist options
  • Save iwamoto-takaaki/8419a7609689695356be3abd59c4af95 to your computer and use it in GitHub Desktop.
Save iwamoto-takaaki/8419a7609689695356be3abd59c4af95 to your computer and use it in GitHub Desktop.
RubyのTimesをC#の拡張メソッドで実装してみた ref: https://qiita.com/takaaki-iwamoto/items/7f59f9768d1e757e74a7
3.times{|i|
p i
}
# out =>
# 0
# 1
# 2
using System;
using System.Linq;
public class Program{
public static void Main(){
Enumerable.Range(0,3).ToList().ForEach(i =>
Console.WriteLine(i)
);
}
}
using System;
public class Program{
public static void Main(){
// Enumerable.Range(0,3).ToList().ForEach(i =>
for(var i = 0; i < 3; ++i){
Console.WriteLine(i);
};
}
}
using System;
using System.Collections.Generic;
using System.Linq;
public class Program{
public static void Main(){
3.Times(i =>
Console.Write(i)
);
}
}
1.upto(3).each{|i|
p i
}
# out =>
# 1
# 2
# 3
using System;
using System.Collections.Generic;
using System.Linq;
public class Program{
public static void Main(){
1.To(3).ToList().ForEach(i =>
Console.Write(i)
);
}
}
// out =>
// 1
// 2
// 3
using System;
using System.Collections.Generic;
using System.Linq;
public class Program{
public static void Main(){
foreach(var i in 1.To(3)) {
Console.Write(i);
};
}
}
using System;
using System.Collections.Generic;
using System.Linq;
public static class Extension{
public static IEnumerable<int> To(this int from, int to){
return Enumerable.Range(from, to - from + 1);
}
}
using System;
using System.Collections.Generic;
using System.Linq;
public class Program{
public static void Main(){
1.To(3).ToList().ForEach(i =>
Console.Write(i)
);
}
}
public static class Extension{
public static IEnumerable<int> To(this int from, int to){
return Enumerable.Range(from, to - from + 1);
}
}
using System;
using System.Collections.Generic;
using System.Linq;
public class Program{
public static void Main(){
3.Times(i =>
Console.Write(i)
);
}
}
public static class Extension{
public static IEnumerable<int> To(this int from, int to){
return Enumerable.Range(from, to - from + 1);
}
// albireoさんの提案のコード追記
public static void ForEach<T>(this IEnumerable<T> source, Action<T> action){
source.All(x => {action(x); return true;});
}
public static void Times(this int times, Action<int> action){
// 0.To(times - 1).ToList().ForEach(x => action(x));
0.To(times - 1).ForEach(x => action(x));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment