为什么我每次调用 IEnumerable.Last() 时都会得到另一个参考
Why I get another reference each time I call IEnumerable.Last()
我有一个可枚举的 (theEnumerable
),其中包含多个项目(引用类型)。
以下表达式 theEnumerable.Last() == theEnumerable.Last()
的计算结果为 false
。
其中:
theEnumerable = Enumerable.Range(1, x).Select(x => new T())
这是为什么?
并非所有序列都必须以相同的顺序 return 相同的值。序列可以在每次迭代时产生不同的值,或者以不同的顺序产生值。
也有可能是所讨论的类型具有重载的相等运算符,导致对象不等于自身。类型 不应该 那样做,但他们在技术上可以。
根据 OP 评论。 Enumerable 创建如下:
Enumerable.Range(1, x).Select(x => new T())
那么当你做 theEnumerable.Last() == theEnumerable.Last()
时会发生什么,你枚举了 theEnumerable
两次,这意味着这个 Select
lambda x => new T()
在你每次迭代 theEnumerable
,这意味着每次迭代都会产生不同的结果,因此造成混乱。
如果您希望您的代码像您期望的那样工作。执行以下操作。
var list = theEnumerable.ToList() // iterate once
list.Last() == list.Last() // I don't see how this makes sense, but I guess you have your own logic
我有一个可枚举的 (theEnumerable
),其中包含多个项目(引用类型)。
以下表达式 theEnumerable.Last() == theEnumerable.Last()
的计算结果为 false
。
其中:
theEnumerable = Enumerable.Range(1, x).Select(x => new T())
这是为什么?
并非所有序列都必须以相同的顺序 return 相同的值。序列可以在每次迭代时产生不同的值,或者以不同的顺序产生值。
也有可能是所讨论的类型具有重载的相等运算符,导致对象不等于自身。类型 不应该 那样做,但他们在技术上可以。
根据 OP 评论。 Enumerable 创建如下:
Enumerable.Range(1, x).Select(x => new T())
那么当你做 theEnumerable.Last() == theEnumerable.Last()
时会发生什么,你枚举了 theEnumerable
两次,这意味着这个 Select
lambda x => new T()
在你每次迭代 theEnumerable
,这意味着每次迭代都会产生不同的结果,因此造成混乱。
如果您希望您的代码像您期望的那样工作。执行以下操作。
var list = theEnumerable.ToList() // iterate once
list.Last() == list.Last() // I don't see how this makes sense, but I guess you have your own logic