在 c#.net 中的现有数组中添加新项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/249452/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 19:52:12  来源:igfitidea点击:

Add new item in existing array in c#.net

c#.net

提问by

How to add new item in existing string array in C#.net?

如何在 C#.net 中的现有字符串数组中添加新项目?

I need to preserve the existing data.

我需要保留现有数据。

回答by Ed S.

I would use a List if you need a dynamically sized array:

如果您需要动态大小的数组,我会使用 List:

List<string> ls = new List<string>();
ls.Add("Hello");

回答by harpo

I agree with Ed. C# does not make this easy the way VB does with ReDim Preserve. Without a collection, you'll have to copy the array into a larger one.

我同意埃德。C# 不像 VB 使用 ReDim Preserve 那样容易做到这一点。如果没有集合,您必须将数组复制到更大的数组中。

回答by Ali Ers?z

That could be a solution;

这可能是一个解决方案;

Array.Resize(ref array, newsize);
array[newsize - 1] = "newvalue"

But for dynamic sized array I would prefer list too.

但是对于动态大小的数组,我也更喜欢列表。

回答by artur02

Arrays in C# are immutable, e.g. string[], int[]. That means you can't resize them. You need to create a brand new array.

C# 中的数组是不可变的,例如string[]int[]。这意味着您无法调整它们的大小。您需要创建一个全新的数组。

Here is the code for Array.Resize:

这是Array.Resize的代码:

public static void Resize<T>(ref T[] array, int newSize)
{
    if (newSize < 0)
    {
        throw new ArgumentOutOfRangeException("newSize", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
    }
    T[] sourceArray = array;
    if (sourceArray == null)
    {
        array = new T[newSize];
    }
    else if (sourceArray.Length != newSize)
    {
        T[] destinationArray = new T[newSize];
        Copy(sourceArray, 0, destinationArray, 0, (sourceArray.Length > newSize) ? newSize : sourceArray.Length);
        array = destinationArray;
    }
}

As you can see it creates a new array with the new size, copies the content of the source array and sets the reference to the new array. The hint for this is the refkeyword for the first parameter.

如您所见,它创建了一个具有新大小的新数组,复制源数组的内容并将引用设置为新数组。对此的提示是第一个参数的ref关键字。

There are lists that can dynamically allocate new slotsfor new items. This is e.g. List<T>. These contain immutable arrays and resize them when needed (List<T> is not a linked list implementation!). ArrayListis the same thing without Generics (with Objectarray).

有些列表可以为新项目动态分配新插槽。这是例如List<T>。这些包含不可变数组并在需要时调整它们的大小(List<T> 不是链表实现!)。ArrayList与没有泛型(使用Object数组)的情况相同。

LinkedList<T>is a real linked list implementation. Unfortunately you can add just LinkListNode<T> elements to the list, so you must wrap your own list elements into this node type. I think its use is uncommon.

LinkedList<T>是一个真正的链表实现。不幸的是,您只能将 LinkListNode<T> 元素添加到列表中,因此您必须将自己的列表元素包装到此节点类型中。我认为它的使用并不常见。

回答by Dave Blake

private static string[] GetMergedArray(string[] originalArray, string[] newArray)
    {
        int startIndexForNewArray = originalArray.Length;
        Array.Resize<string>(ref originalArray, originalArray.Length + newArray.Length);
        newArray.CopyTo(originalArray, startIndexForNewArray);
        return originalArray;
    }

回答by Gia Duong Duc Minh

string str = "string ";
List<string> li_str = new List<string>();
    for (int k = 0; k < 100; i++ )
         li_str.Add(str+k.ToString());
string[] arr_str = li_str.ToArray();

回答by Stephen Chung

Using LINQ:

使用 LINQ:

arr = (arr ?? Enumerable.Empty<string>()).Concat(new[] { newitem }).ToArray();

I like using this as it is a one-liner and very convenient to embed in a switch statement, a simple if-statement, or pass as argument.

我喜欢使用它,因为它是单行的,非常方便嵌入 switch 语句、简单的 if 语句或作为参数传递。

EDIT:

编辑:

Some people don't like new[] { newitem }because it creates a small, one-item, temporary array. Here is a version using Enumerable.Repeatthat does not require creating any object (at least not on the surface -- .NET iterators probably create a bunch of state machine objects under the table).

有些人不喜欢,new[] { newitem }因为它创建了一个小的、单项的临时数组。这是一个Enumerable.Repeat不需要创建任何对象的版本(至少不是在表面上 - .NET 迭代器可能会在表下创建一堆状态机对象)。

arr = (arr ?? Enumerable.Empty<string>()).Concat(Enumerable.Repeat(newitem,1)).ToArray();

And if you are sure that the array is never nullto start with, you can simplify it to:

如果您确定数组永远不会null开始,您可以将其简化为:

arr.Concat(Enumerable.Repeat(newitem,1)).ToArray();

Notice that if you want to add items to a an ordered collection, Listis probably the data structure you want, not an array to start with.

请注意,如果要将项目添加到有序集合中,List可能是您想要的数据结构,而不是开始时的数组。

回答by aevanko

Why not try out using the Stringbuilderclass. It has methods such as .insert and .append. You can read more about it here: http://msdn.microsoft.com/en-us/library/2839d5h5(v=vs.71).aspx

为什么不尝试使用Stringbuilder类。它有 .insert 和 .append 等方法。您可以在此处阅读更多相关信息:http: //msdn.microsoft.com/en-us/library/2839d5h5(v=vs.71).aspx

回答by tmania

 Array.Resize(ref youur_array_name, your_array_name.Length + 1);
 your_array_name[your_array_name.Length - 1] = "new item";

回答by JAR

Unfortunately using a list won't work in all situations. A list and an array are actually different and are not 100% interchangeable. It would depend on the circumstances if this would be an acceptable work around.

不幸的是,使用列表并不适用于所有情况。列表和数组实际上是不同的,不能 100% 互换。如果这是一个可以接受的解决方法,这将取决于具体情况。