by Kofi Sarfo
6. June 2009 00:02
Reminded recently of a method for determining Prime Numbers (Sieve of Eratosthenes) and saw some Generic Collection Class action (p. 97 C# In Depth)
List<int> candidates = new List<int>();
for (int i = 2; i <= 100; i++)
{
candidates.Add(i);
}
for (int factor = 2; factor <= 10; factor++)
{
candidates.RemoveAll(delegate(int x)
{ return x > factor && x % factor == 0; }
);
}
candidates.ForEach(delegate(int prime)
{ Console.WriteLine(prime); }
);
Bouncing around looking for code samples to see what we're missing in terms of Generics... we spot something. Switch on the Code: The Built-In Generic Delegate Declarations.
Difference between Func<T> and Action<T> is the latter doesn't have a return type. Too obvious to miss? Maybe. Quick search shows difference between new Action() and Lambda at Stack Overflow. Response from author of code sample above. Jon Skeet. 3900 answers on Stack Overflow in 8 months. Or 16 answers a day, every day.
Notes:
MSDN: Lambda Expressions
CodeBetter: Back to Basics - Delegates, Anonymous Methods and Lambda Expressions