Click here to Skip to main content
15,902,189 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I meet a problem during learnning LINQ through《LINQ Pocket Reference》

C#
IEnumerable<char> query = "Not what you might expect";
foreach (char vowel in "aeiou")
   {
     char temp = vowel;
     query = query.Where(c => c != temp);

   }
   foreach (char n in query)
   {
      Response.Write(n + " ");
   }

/*follow is comment by author:
Without the temporary variable,the query will use the most recent value of vowel ("u") on each successive filter,so only the "u" characters will be removed.*/

Why???
Posted
Updated 16-Nov-12 23:38pm
v2

1 solution

C#
foreach (char vowel in "aeiou")
{
  query = query.Where(c => c != vowel);
}
foreach (char n in query)
{
  Console.Write(n + " ");
}


I don't know how foreach loop have inside it but I suspect that it's single variable of given type.
So in when adding a reference in your Where lamba to it your adding same reference.
Change reference in next foreach iteration and all values will change cause of all are pointing to same variable.

Temp variable will solve this since in each iteration you are declaring new with diffrent variable.

And it is query it is not executed till time when you get it's value so something along the lines:

C#
char[] s = "Not what you might expect".ToArray();
foreach (char vowel in "aeiou")
{
  s = s.Where(c => c != vowel).ToArray();
}
foreach (char n in query)
{
  Console.Write(n + " ");
}


will solved it to.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900