Monday, September 12, 2011

Closure Example (C#)

1.

IEnumerable<char> query = "Not what you might expect";
    query = query
               .Where(c => c != 'a')
               .Where(c => c != 'e')
               .Where(c => c != 'i')
               .Where(c => c != 'o')
               .Where(c => c != 'u');

 

result

// Nt wht y mght xpct

2.

 

IEnumerable<char> query = "Not what you might expect";
foreach (char vowel in "aeiou")
                  query = query.Where (c => c != vowel);
foreach (char c in query) Console.Write (c);

 

Result :

// Not what yo might expect

(only u is skipped, because vowel is updated on foreach step, when later enumberate the query, all lambda expression reference same charter value which is ā€œuā€ , and executed five same times).

 

3. Workout solution

IEnumerable<char> query = "Not what you might expect";
foreach (char vowel in "aeiou")
{               

char kk=vowel;

  query = query.Where (c => c != kk);
}

foreach (char c in query) Console.Write (c);

 

Result:

// Nt wht y mght xpct

0 Comments:

Post a Comment

<< Home