Captured Variables

If the query's lambda expressions reference local variables and you later change their value, the query changes as well.

 
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
class Program
{
    static void Main()
    {
        int[] numbers = { 1, 2 };

        int factor = 10;
        IEnumerable<int> query = numbers.Select(n => n * factor);
        factor = 20;
        foreach (int n in query) Console.Write(n + "|");

    }
}
  

The output:


20|40|

Compare the following two examples:

 
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
class Program
{
    static void Main()
    {
        IEnumerable<char> query = "aeiou";

        query = query.Where(c => c != 'a');
        query = query.Where(c => c != 'e');

        foreach (char ch in query)
            Console.WriteLine(ch);
    }
}
  

The output:


i
o
u
 
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
class Program
{
    static void Main()
    {
        IEnumerable<char> query = "aeiou";

        foreach (char vowel in "ae")
            query = query.Where(c => c != vowel);

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

The output:


aiou

To solve this, we can assign the loop variable to another variable:

 
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
class Program
{
    static void Main()
    {
        IEnumerable<char> query = "aeiou";

        foreach (char vowel in "ae")
        {
            char temp = vowel;
            query = query.Where(c => c != temp);
        }
    }
}
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.