Reputation: 12923
In C# I have three arrays, string[] array1
, 2 and 3 and they all have differnt values. I would love to do what I can do in php which is:
$array = array();
$array[] .= 'some value';
Whats the equivalent way of doing this in C#?
Upvotes: 0
Views: 208
Reputation: 564413
In C#, you'd typically use a List<string>
instead of string[]
.
This will allow you to write list.Add("some value")
and will "grow" the list dynamically.
Note that it's easy to convert between a list and an array if needed. List<T>
has a constructor that takes any IEnumerable<T>
, including an array, so you can make a list from an array via:
var list = new List<string>(stringArray);
You can convert a list to an array via:
var array = list.ToArray();
This is only required if you need an array, however (such as working with a third party API). If you know you're going to work with collections that vary in size, it's often better to just always stick to List<T>
and not use arrays.
Upvotes: 7
Reputation: 19646
Easy with linq:
int[] array1 = { 1, 2, 3, 4, 5 };
int[] array2 = { 6, 7, 8, 9, 10 };
int[] array3 = { 3, 4 ,5, 9, 10 };
var result = array1
.Concat(array2)
.Concat(array3)
.ToArray();
Upvotes: 0
Reputation: 12375
if you simply want to merge your arrays
use linq .Concat
array1 = array1.Concat(array2).Concat(array3).ToArray();
Upvotes: 0
Reputation: 40393
List<T>
or LINQ may be the easiest solutions, but you can also do it the old fashioned way:
// b1 is now 5 bytes
byte[] b1 = Get5BytesFromSomewhere();
// creating a 6-byte array
byte[] temp = new byte[6];
// copying bytes 0-4 from b1 to temp
Array.copy(b1, 0, temp, 0, 5);
// adding a 6th byte
temp[5] = (byte)11;
// reassigning that temp array back to the b1 variable
b1 = temp;
Upvotes: 0
Reputation: 8902
You can create a list and add the array values to it and then convert that list back to array.
int[] array1 = { 1, 2, 3, 4, 5 };
int[] array2 = { 6, 7, 8, 9, 10 };
// Create new List of integers and call AddRange twice
var list = new List<int>();
list.AddRange(array1);
list.AddRange(array2);
// Call ToArray to convert List to array
int[] array3 = list.ToArray();
Upvotes: 2
Reputation: 86600
You could use dinamic lists List<string>
. You can do
List<string> TotalList = array1.ToList();
Then you can TotalList.AddRange(array2)
and so on....
Upvotes: 0