考虑以下类:
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();
}
}
以下功能:
public IEnumerable<Score> GetScores()
{
yield return new Score();
yield return new Score();
yield return new Score();
}
为什么以下函数返回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();
}
但是当我添加.ToList()
到filteredScores
(在 foreach 循环中或在 linq 操作之后)时,函数的结果是3。
我怀疑它与关闭循环变量有关,但我似乎无法弄清楚这一点。