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();
}
}
Next function:
public IEnumerable<Score> GetScores()
{
yield return new Score();
yield return new Score();
yield return new Score();
}
Why this 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()in filteredScores(either in the foreach loop or after the linq operation), the result of function 3 .
I suspect this has something to do with Closing on a loop variable , but I can't seem to figure this out.
source
share