Wednesday, July 16, 2008

List Comprehension in C# with LINQ

List comprehensions from Python (from Haskell) miss me a lot in C#
Happily with LINQ I dont miss then anymore :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ListComprehension
{
class Program
{
static void Main(string[] args)
{
string[] countries = { "Britain", "France", "Croatia", "Argentina", "Australia", "Mexico", "Finland",
"Spain", "Italy", "Greece" };

string[] favcountries = { "Britain", "Argentina", "Greece", "Brazil" };

var thecountries = from c in countries
where favcountries.Contains(c)
select c;

foreach (var c in thecountries)
{
Console.WriteLine(c);
}
Console.ReadLine();
}
}
}

No comments:

Post a Comment