IEnumerable的重复功能 [英] IEnumerable repeats function

查看:108
本文介绍了IEnumerable的重复功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我面临一个奇怪的问题。在这里我转载了问题。

I have faced a strange problem. Here I reproduced the problem.

Random r = new Random();
List<int> x = new List<int> {1, 2, 3, 4, 5, 6};

var e = x.OrderBy(i => r.Next());
var list1 = e.ToList();
var list2 = e.ToList();

bool b = list1.SequenceEqual(list2);
Console.WriteLine(b); // prints false



到现在为止,我还以为他们是所谓当Linq的功能得到执行。但是,这个方法看来以后我称之为了ToList LINQ的功能排序依据再次执行。为什么会这样?

Until now, I thought that Linq functions get executed when they are called. But, in this method it seems after I call ToList the Linq function OrderBy executes again. Why is that so?

推荐答案

您正在寻找延迟执行。当你创建一个LINQ查询它基本上是一个蓝图,上面写着要求时,执行这些步骤来操作数据源。这里最棘手的部分是,这个请求仅由一组不同的LINQ操作( .ToList()是其中之一)。

You're looking at deferred execution. When you create a LINQ query it's basically a blueprint that says "when requested, perform these steps to manipulate the datasource". The tricky part here is that this request is only done by a distinct set of LINQ operations (.ToList() is one of these).

所以,当你调用 e.ToList()一旦将随机数据源,因为这是蓝图说,它有什么做的。当你再调用 .ToList()再次同样的蓝图,它再次从一开始就开始,并再次随机化。

So when you call e.ToList() once it will randomize the data source because that's what the blueprint says it has to do. When you then call .ToList() again on this same blueprint, it starts again from the start and randomizes again.

有一个蓝图,不包含任何状态下,它只是说我应该在每一步的方式来完成。

A blueprint doesn't contain any state, it just says what should be done at each step of the way.

这篇关于IEnumerable的重复功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆