3

Consider the following class:

public class Score
{
    private static readonly Guid _relationId = Guid.NewGuid();

    public Guid Id { get; set; }
    public Guid RelationId { get { return _relationId; } }

    public Score()
    {
        Id = Guid.NewGuid();
    }
}

The following function:

public IEnumerable<Score> GetScores()
{
    yield return new Score();
    yield return new Score();
    yield return new Score();
}

Why is it that the following function returns 1:

public int Execute()
{
    var scores = GetScores();
    IList<Score> externalScores = new List<Score>();

    var filteredScores = scores.Where(score => externalScores.All(x => x.RelationId != score.RelationId));

    foreach (var score in filteredScores)
    {
        externalScores.Add(score);
    }

    return externalScores.Count();
}

But when I add .ToList() to filteredScores (either in the foreach loop or after the linq operation) the result of the function is 3.

I suspect it has something to do with Closing over the loop variable, but I can't seem to figure this out.

1
  • Your code currently has ToList() in it already; I assume you forgot to take it out.
    – Rawling
    May 22, 2012 at 11:37

1 Answer 1

6

With ToList, all items in scores are checked if they match the predicate, which returns always true because externalScores is empty.

Without ToList, each item in scores is checked interleaved with the foreach loop (see: Deferred Execution) which modifies externalScores, causing the predicate to return true for the first item and false for the other two items.

2
  • 1
    I was trying to figure out why filteredScores returned empty after externalScores had an item added - I'd totally missed that all the RelationId properties return the same GUID.
    – Rawling
    May 22, 2012 at 11:51
  • Brilliant, never thought of that.
    – Lodewijk
    May 22, 2012 at 11:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.