HashSet 上的 LINQ 的 ForEach?
我很好奇什么限制使得设计决策必须使 HashSet 不能使用 LINQ 的 ForEach 查询。
这两个实现的幕后真正发生的事情不同:
var myHashSet = new HashSet<T>;
foreach( var item in myHashSet ) { do.Stuff(); }
vs
var myHashSet = new HashSet<T>;
myHashSet.ForEach( item => do.Stuff(); }
我(非常)确定这只是因为 HashSet 没有实现 IEnumerable ——但是正常的 ForEach 循环的不同做法是什么,使其更受 HashSet 支持?
谢谢
I am curious as to what restrictions necessitated the design decision to not have HashSet's be able to use LINQ's ForEach query.
What's really going on differently behind the scenes for these two implementations:
var myHashSet = new HashSet<T>;
foreach( var item in myHashSet ) { do.Stuff(); }
vs
var myHashSet = new HashSet<T>;
myHashSet.ForEach( item => do.Stuff(); }
I'm (pretty) sure that this is just because HashSet does not implement IEnumerable -- but what is a normal ForEach loop doing differently that makes it more supported by a HashSet?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
LINQ 没有
ForEach
。只有List
类具有ForEach
方法。还需要注意的是,HashSet 确实实现了
IEnumerable
。请记住,LINQ 代表语言集成查询。它的目的是查询数据集合。
ForEach
与查询无关。它只是循环数据。因此它确实不属于 LINQ。LINQ doesn't have
ForEach
. Only theList<T>
class has aForEach
method.It's also important to note that HashSet does implement
IEnumerable<T>
.Remember, LINQ stands for Language INtegrated Query. It is meant to query collections of data.
ForEach
has nothing to do with querying. It simply loops over the data. Therefore it really doesn't belong in LINQ.LINQ 的目的是查询数据,我猜它避免了
ForEach()
因为它有可能改变数据,从而影响数据的查询方式(即,如果您更改了影响数据的字段)哈希码或相等)。您可能对
List
有一个ForEach()
感到困惑?当然,编写一个很容易,但由于上述问题,应谨慎使用......
LINQ is meant to query data, I'm guessing it avoided
ForEach()
because there's a chance it could mutate data that would affect the way the data could be queried (i.e. if you changed a field that affected the hash code or equality).You may be confused with the fact that
List<T>
has aForEach()
?It's easy enough to write one, of course, but it should be used with caution because of those aforementioned concerns...
首先使用HashSet的GetEnumerator方法
第二个方法 ForEach
也许第二个在幕后使用 GetEnumerator 但我不确定。
The first use the method GetEnumerator of HashSet
The second the method ForEach
Maybe the second use GetEnumerator behind the scene but I'm not sure.