Have you noticed this function in C# 2.0
This is really weird, I've been using C# 2.0 since beta 2, and I didn't notice this function in List class
Consider the following code.
class Program
{
static void Main(string[] args)
{
List<int> list = new List<int>();
for (int i = 0; i < 100; i++)
{
list.Add(i);
}
list.ForEach(delegate(int i) { Console.WriteLine(i); });
}
}
This is a simple program that creates a new List<int> and initialize it with numbers from 0 to 99.
but consider the last line,
list.ForEach it takes a delegate of type Action<T> which accepts a parameter of type T, and returns nothing, so it is perfect at performing actions like printing out all the list elements or any similar action without writing the ForEach loop.
This is really similar to Ruby syntax, if you are familiar with stuff like this
>> stuff.each do |thing|
.. print thing
.. print "\n"
.. end
and it will be even better with C# 3.0 because it will be very concise consider it this way.
class Program
{
static void Main(string[] args)
{
List<int> list = new List<int>();
list.AddRange(Sequence.Range(0, 100));
list.ForEach(i => Console.WriteLine(i) );
}
}
as you can see Lambda Expressions is playing well, also the new Sequence.Range which is similar to range() method in Python
Functional Programming is coming back guys ;)
Digg It