IEnumerable.Concat —— 无需更改引用即可工作的替代品?
我最近被 Concat
返回结果而不是附加到列表本身的问题所困扰(在我看来这太常见了)。
例如。
List<Control> mylist=new List<Control>;
//.... after adding Controls into mylist
MyPanel.Controls.Concat(mylist); //This will not affect MyPanel.Controls at all.
MyPanel.Controls=MyPanel.Controls.Concat(mylist); //This is what is needed, but the Controls reference can not be reassigned (for good reason)
那么,当集合引用为只读时,是否有其他方法可以组合两个列表?
这是使用 foreach 执行此操作的唯一方法吗?
foreach(var item in mylist){
MyPanel.Controls.Add(item);
}
没有 foreach 有更好的方法吗?
I've recently been bitten by the (way too commmon in my opinion) gotcha of Concat
returns it's result, rather than appending to the list itself.
For instance.
List<Control> mylist=new List<Control>;
//.... after adding Controls into mylist
MyPanel.Controls.Concat(mylist); //This will not affect MyPanel.Controls at all.
MyPanel.Controls=MyPanel.Controls.Concat(mylist); //This is what is needed, but the Controls reference can not be reassigned (for good reason)
So is there some other way of combining two lists that will work when the collection reference is read-only?
Is the only way to do this with a foreach?
foreach(var item in mylist){
MyPanel.Controls.Add(item);
}
Is there a better way without the foreach?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
许多集合都有一个 AddRange 方法,winforms ControlCollection 就是其中之一。
这样做的好处是告诉容器您将一次添加许多控件,因此它可能会延迟布局步骤,直到添加完所有控件为止。
Many collections have an AddRange method, winforms ControlCollection is one of them.
This has the benefit of telling the container you'll be adding many controls at once, so it may delay layout steps until it's done adding all of them.
您的问题询问有关 IEnumerable 的问题,答案始终是“否” - IEnumerable 是项目的只进“流”。
但是,如果您可以使用更专业的类型 - ICollection、IList 等 - 那么您可以使用 Add 或 AddRange 方法(如果可用)。
Your question asks about IEnumerable, and the answer to that is always "No" - an IEnumerable is a forward-only "stream" of items.
However, if you can use a more Specialized type - ICollection, IList etc. - then you can use the Add or AddRange methods if available.
然后你就有了:
当然,一些集合(
List
、ControlCollection
等)已经拥有一个AddRange
-这只是让那些没有的人可以使用它。Then you have:
Of course some collections (
List<T>
,ControlCollection
etc) already have anAddRange
- this simply makes it available to those that don't.极少数情况下,您更喜欢大写的 ForEach 而不是小写的 foreach:
In the off-chance you prefer capitalized ForEach over lowercase foreach: