Domanda

I'm trying to write a simple chat box, and I found a really simple piece of code for it on the unity forums, but its in UnityScript (similar to JavaScript).

I tried to convert the code to C# and I've had some success, but the problem is that the code uses Array.Unshift(), which prepends an item to an array. I'm trying to find some simple way of doing this in C#, but for the life of me I can't get it to work.

What is the C# equivalent of Array.Unshift?

È stato utile?

Soluzione

As per my understanding .Unshift method adds items to the start of array and return new length of array.

You can use List<T> collection in C#. To add items at first position of (prepond) to list use following way.

List<T>.Insert(0, item); // this will insert item at first position

Also you can convert this list to array using .ToArray() method of list.

Altri suggerimenti

It's tricky with C# arrays. You need to make a new array and copy all elements from the old one, plus the extra element to insert. I suggest using List<T> instead, or maybe rethink the algorithm so it doesn't need it.

If you import System.Linq it also adds .Prepend(T obj) to IEnumerable<T> which includes arrays.

using System.Linq;

//...
int[] example = new int[]{1,2,3};
int[] updated = example.Prepend(0);//{0,1,2,3}
//..

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top