Best way to “push” into C# array

后端 未结 12 2630
没有蜡笔的小新
没有蜡笔的小新 2021-02-13 14:25

Good day all

So I know that this is a fairly widely discussed issue, but I can\'t seem to find a definitive answer. I know that you can do what I am asking for using a L

12条回答
  •  无人共我
    2021-02-13 14:33

    array.push is like List.Add. .NET arrays are fixed-size so you can't actually add a new element. All you can do is create a new array that is one element larger than the original and then set that last element, e.g.

    Array.Resize(ref myArray, myArray.Length + 1);
    myArray[myArray.GetUpperBound(0)] = newValue;
    

    EDIT:

    I'm not sure that this answer actually applies given this edit to the question:

    The crux of the matter is that the element needs to be added into the first empty slot in an array, lie a Java push function would do.

    The code I provided effectively appends an element. If the aim is to set the first empty element then you could do this:

    int index = Array.IndexOf(myArray, null);
    
    if (index != -1)
    {
        myArray[index] = newValue;
    }
    

    EDIT:

    Here's an extension method that encapsulates that logic and returns the index at which the value was placed, or -1 if there was no empty element. Note that this method will work for value types too, treating an element with the default value for that type as empty.

    public static class ArrayExtensions
    {
        public static int Push(this T[] source, T value)
        {
            var index = Array.IndexOf(source, default(T));
    
            if (index != -1)
            {
                source[index] = value;
            }
    
            return index;
        }
    }
    

提交回复
热议问题