为什么每次访问变量时都会调用LINQ查询?
为什么在下面的代码中再次调用Square()
?我想价值正在重新计算,但是为什么呢?我们之前获得了value
,为什么再次被调用?为什么编译器发出警告“可能的多重枚举”?
static IEnumerable<int> Square(IEnumerable<int> a)
{
foreach(var r in a)
{
Console.WriteLine($"From Square {r * r}");
yield return r * r;
}
}
class Wrap
{
private static int init = 0;
public int Value
{
get { return ++init; }
}
}
static void Main(string[] args)
{
var w = new Wrap();
var wraps = new Wrap[3];
for(int i=0; i<wraps.Length; i++)
{
wraps[i] = w;
}
var values = wraps.Select(x => x.Value);
var results = Square(values);
int sum = 0;
int count = 0;
foreach(var r in results)
{
count++;
sum += r;
}
Console.WriteLine("Count {0}", count);
Console.WriteLine("Sum {0}", sum);
Console.WriteLine("Count {0}", results.Count());
Console.WriteLine("Sum {0}", results.Sum());
}
结果:
From Square 1
From Square 4
From Square 9
Count 3
Sum 14
From Square 16
From Square 25
From Square 36
Count 3
From Square 49
From Square 64
From Square 81
Sum 194
Why is Square()
being called again in the code below? I suppose values is being recalculated, but why? We got the values
earlier, why is it being called again? Why does the compiler issue a warning "Possible multiple enumeration"?
static IEnumerable<int> Square(IEnumerable<int> a)
{
foreach(var r in a)
{
Console.WriteLine(quot;From Square {r * r}");
yield return r * r;
}
}
class Wrap
{
private static int init = 0;
public int Value
{
get { return ++init; }
}
}
static void Main(string[] args)
{
var w = new Wrap();
var wraps = new Wrap[3];
for(int i=0; i<wraps.Length; i++)
{
wraps[i] = w;
}
var values = wraps.Select(x => x.Value);
var results = Square(values);
int sum = 0;
int count = 0;
foreach(var r in results)
{
count++;
sum += r;
}
Console.WriteLine("Count {0}", count);
Console.WriteLine("Sum {0}", sum);
Console.WriteLine("Count {0}", results.Count());
Console.WriteLine("Sum {0}", results.Sum());
}
Results:
From Square 1
From Square 4
From Square 9
Count 3
Sum 14
From Square 16
From Square 25
From Square 36
Count 3
From Square 49
From Square 64
From Square 81
Sum 194
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
square(values)
返回iEnumerable
,每次访问时都会迭代(调用)。如果将结果投放到
list()
,则将结果凝结到list()
中。带有
.tolist()
的结果Square(values)
returns anIEnumerable
, which is iterated over (called) each time it is accessed.If you cast the result to a
List()
, the results are concreted into aList()
.Results with
.ToList()