Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 5979033
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 22, 20262026-05-22T21:36:08+00:00 2026-05-22T21:36:08+00:00

I have a scope question regarding Linq expressions that are defined in a loop.

  • 0

I have a scope question regarding Linq expressions that are defined in a loop. The following LinqPad C# Program demonstrates the behaviour:

void Main()
{
    string[] data=new string[] {"A1", "B1", "A2", "B2" };
    string[] keys=new string[] {"A", "B" };

    List<Result> results=new List<Result>();

    foreach (string key in keys) {
        IEnumerable<string> myData=data.Where (x => x.StartsWith(key));     
        results.Add(new Result() { Key=key, Data=myData});          
    }   
    results.Dump();
}

// Define other methods and classes here
class Result {
    public string Key { get; set; }
    public IEnumerable<string> Data { get; set; }
}

Basically, “A” should have data [A1, A2] and “B” should have data [B1, B2].

However, when you run this “A” gets data [B1, B2] as does B. I.e. the last expression is evaluated for all instances of Result.

Given that I declared “myData” inside the loop, why is it behaving as if I declared it outside the loop? EG it is acting like I would expect if I did this:

void Main()
{
    string[] data=new string[] {"A1", "B1", "A2", "B2" };
    string[] keys=new string[] {"A", "B" };

    List<Result> results=new List<Result>();

    IEnumerable<string> myData;                 
    foreach (string key in keys) {
        myData=data.Where (x => x.StartsWith(key));     
        results.Add(new Result() { Key=key, Data=myData});          
    }   
    results.Dump();
}

// Define other methods and classes here
class Result {
    public string Key { get; set; }
    public IEnumerable<string> Data { get; set; }
}

I get the desired result if I force the evaluation inside the iteration, that is not my question.

I’m asking why “myData” is seemingly shared across iterations given that I declared it within scope of a single iteration?

Somebody call Jon Skeet… ;^)

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-22T21:36:09+00:00Added an answer on May 22, 2026 at 9:36 pm

    It’s not myData which is being shared – it’s key. And as the values within myData are evaluated lazily, they depend on the current value of key.

    It’s behaving that way because the scope of the iteration variable is the whole loop, not each iteration of the loop. You’ve got a single key variable whose value changes, and it’s the variable which is captured by the lambda expression.

    The correct fix is just to copy the iteration variable into a variable within the loop:

    foreach (string key in keys) {
        String keyCopy = key;
        IEnumerable<string> myData = data.Where (x => x.StartsWith(keyCopy));     
        results.Add(new Result() { Key = key, Data = myData});
    }
    

    For more information about this problem, see Eric Lippert’s blog post “Closing over the loop variable considered harmful”: part one, part two.

    It’s an unfortunate artifact of the way the language has been designed, but changing it now would be a bad idea IMO. Although any code which changed behaviour would basically have been broken beforehand, it would mean that correct code in (say) C# 6 would be valid but incorrect code in C# 5, and that’s a dangerous position to be in.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm new to Java and have the following question regarding inner classes: When implementing
My question is regarding the scope of the object created in +planet. I have
A question regarding the scopes of Seam out params. Suppose I have @Out(required =
I'm new to C++, and I have a question that should be easy, but
What is the scope of variables in javascript? Do they have the same scope
I have a number of application settings (in user scope) for my custom grid
I have a JQuery silder that I'm using to set the score on a
I have a piece of XML that is structured similar to this: <root> <score
I'm currently developing some things in Python and I have a question about variables
In my application, I've got several ViewModels that have a single service (repository, DAO,

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.