using System;
using System.Linq;
using System.Collections.Generic;
public class FunctionalStyleProgramming
{
private static void PrintList(IEnumerable<int> list)
{
foreach(int elem in list){
Console.Write(elem);
Console.Write(' ');
}
Console.WriteLine();
}
/// Problem: You need to get a list that contains even numbers
/// ranged from 0 up to 100
///
public static void Main()
{
// First, using the traditional for-loop
var even_numbers_for = new List<int>();
even_numbers_for.Capacity = 100;
for(int i = 0; i < 100; ++i){
if(i % 2 == 0)
even_numbers_for.Add(i);
}
// Second, using the slightly sophisticated foreach-loop
var even_numbers_foreach = new List<int>();
even_numbers_foreach.Capacity = 100;
foreach(int j in Enumerable.Range(0, 100)){
if(j % 2 == 0)
even_numbers_foreach.Add(j);
}
// Third, using LINQ to Objects
var even_numbers_lto =
Enumerable.Range(0, 100)
.Where(n => n % 2 == 0);
// And lastly using LINQ to SQL(which I strongly recommend to use, and is familiar to those who are used to SQL)
var even_numbers_lts =
from n in Enumerable.Range(0, 100)
where n % 2 == 0
select n;
//Darn Ideone! It doesn't hightlight LINQ to SQL syntaxes! I'm very disappointed at that ;-(
PrintList(even_numbers_for);
PrintList(even_numbers_foreach);
PrintList(even_numbers_lto);
PrintList(even_numbers_lts);
// And then think about the pros and cons of each solution.
// Which one do you think is the best solution?
//
// Extra...
Note();
}
private static void Note()
{
var first_even_number =
(from n in Enumerable.Range(1, 100)
where n % 2 == 0
select n
).FirstOrDefault();
Console.WriteLine("The first even number above 0 is {0}.", first_even_number);
var recommended =
from n in Enumerable.Range(1, 100)
where n % 2 == 0
select n;
var recommended_first_even_number = recommended.FirstOrDefault();
Console.WriteLine("The first even number above 0 is {0}.", recommended_first_even_number);
}
}