Add item to array []

I have a class that has a string string [] property.

I need to create another element of the array, do I need to reset the size and copy all the previous elements?

+3
source share
8 answers

You can use Array.Resizethat will save the contents of the array.

eg.

var array = myClass.SomeArrayProperty;
Array.Resize(ref array, newSize);
myClass.SomeArrayProperty = array;

You need to use a temporary variable because properties cannot be used as arguments ref.

+14
source

, , , , IList<string>, ICollection<string> IEnumerable<string>, , , . , , List<string> .

+6

, , List.

, List , IList<string> IEnumerable<String>.

+5

, . . , , .

List<string> myList = new List<string>();
            myList.Add("item");
            myList.Remove("item");

,

Array.Resize

+3

. .

#:

12.2
...
, . , , .

+1

[] List <string> , , .ToArray(), [].

+1

? , List<string> .

( , IList<string> API string[].)

0

List<T>, , . , , IIRC , , .

, , :

public static T[] Append<T>(this T[] arr, T item) {
    Array.Resize(ref arr, arr == null ? 1 : (arr.Length + 1));
    arr[arr.Length-1] = item;
    return arr;
}

:

obj.SomeProp = obj.SomeProp.Append(someValue);

( , , obj.SomeProp null, 1)

/, ref:

public static void Append<T>(ref T[] arr, T item) {
    Array.Resize(ref arr, arr == null ? 1 : (arr.Length + 1));
    arr[arr.Length-1] = item;
}
0
source

Source: https://habr.com/ru/post/1719294/


All Articles