向数组添加元素 [英] Adding an element to an array

查看:91
本文介绍了向数组添加元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从源中读取数据作为数组. a [n]

I m reading data from a source as array. a[n]

我需要在数组中再添加一个元素.

I need to add one more element to the array.

一旦获得数组,我将创建一个容量为n + 1的新数组,并将所有元素复制到新数组中,并将新元素作为数组的最后一个元素.

Once i get the array, i create a new array with capacity n+1 and copy all the elements to the new array and put the new element as the last element of the array.

我可以做到.

是否有更好的方法可以做到这一点?尤其是Linq?

Is there a better way to do this? especially with Linq?

推荐答案

您所描述的确实是唯一的方法.无法在.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.

这篇关于向数组添加元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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