Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse an array of objects

Tags:

arrays

c#

.net

I have a static class containing arrays of objects.

public static Waypoint[] AtoB
        {
            get
            {
                return new Waypoint[] {
                    new Waypoint(49.251f,-851.837f),
                    new Waypoint(66.7397f,-843.165f),
                    new Waypoint(77.8777f,-825.462f)
                };
            }
        }

Now I want to create another array of Waypoint called BtoA that is the same as AtoB but reverse order. So something like:

public static Waypoint[] BtoA
    {
        get { return AtoB.Reverse(); }
    }

Is this possible?


1 Answers

You can save reversed sequence to new array with ToArray() extension call:

return AtoB.Reverse().ToArray();

In this case you will have two arrays in memory - you will have array returned by AtoB property, then you will create reverse iterator for that array, and finally you will save reversed sequence to completely new array.

Or you can reverse original array with Array.Reverse(array):

var array = AtoB;
Array.Reverse(array);
return array;

In this case you will have single array which was created in AtoB property - you just reverse items of that array instance.

NOTE: Your code is not working, because Reverse() extension creates ReverseIterator which is not an array - it is of type IEnumerable<Waypoint>. So, one more option for you is changing type of BtoA property to IEnumerable<Waypoint>.

like image 175
Sergey Berezovskiy Avatar answered Oct 17 '25 06:10

Sergey Berezovskiy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!