更新时间:2022-06-03 22:30:03
您所描述的确实是唯一的方法.无法在.NET中调整数组的大小,因此我们必须分配一个新数组并将旧数组复制到其中.例如,这就是Array.Resize
的工作方式. LINQ在这里并不是真正的帮助,如果有的话,它将只是将现有的数组投影到一个新的数组中-这正是我们刚刚描述的.
What you have described is really the only way to do it. Arrays cannot be resized in .NET, so we have to allocate a new array and copy the old into it. For example, this is how Array.Resize
works. LINQ is not really a help here, and if it was, it would just be projecting the existing array into a new one anyway - which is exactly what we've just described.
如果发现需要经常调整数组大小,则应考虑使用ArrayList
或强类型的List<T>
.
If you find you need to resize the array often, you should consider using an ArrayList
or, if possible, a strongly-typed List<T>
.
修改:
如果只是从某种无法控制的方法中获取一个数组,但是在代码中可以使用IEnumerable<T>
,则可以使用LINQ进行惰性枚举并保留多余的数组分配:
Edit:
If you are simply getting an Array from some method you cannot control, but within your code you could use an IEnumerable<T>
instead, you can use LINQ to lazy-enumerate and spare the extra array allocation:
var mySequence = originalArray.Concat(new[]{myobj});
//snip
foreach(var item in mySequence)
{
//do stuff
}
仅当调用ToArray()
时,我们才会产生额外的开销.否则,我们只是在原始数组上进行一次枚举,然后在末尾偷偷放入多余的项.
It's only when calling ToArray()
that we incur the extra overhead. Otherwise we're simply doing a single enumeration over the original array and then sneaking the extra item(s) in at the end.