Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I cannot get my last index to be the first index C#

Tags:

c#

I have an array list that I'm copying from another method I have made but I just need to reverse it and swap the last value to be the first value. I have thought about doing it this way but for some reason the Prepend is not working at all. RemoveAt is working however. is there an alternative to what I am doing that can get this work?

List<double> pointy = new List<double>
            {
                0,
                FrameHeight-24,
                FrameHeight-24+2,
                FrameHeight-24+2,
                FrameHeight-24+2-3,
                FrameHeight-24+2-3,
                FrameHeight-24+2-3+1,
                FrameHeight-24+2-3+1+2,
                FrameHeight-24+2-3+1+2,
                FrameHeight-24+2-3+1,
                FrameHeight-24+2-3,
                FrameHeight-24+2-3,
                FrameHeight-24+2,
                FrameHeight-24+2,
                FrameHeight-24+2+2,
                FrameHeight,
                FrameHeight,
                0,
                0
            };

            pointy.Prepend(pointy[(pointy.Count) - 1]).ToList();
            pointy.RemoveAt((pointy.Count)-1);
            pointy.Reverse();
like image 902
Joelad Avatar asked Dec 15 '25 02:12

Joelad


1 Answers

If you study the docs, as others link to, you'll see that Prepend() and ToList() don't work exactly like you think, In particular, there is absolutely no point in calling .ToList() without using the returned value.

Instead, there already exists a method on the List class which does exactly what you want:

pointy.Insert(0, pointy[pointy.Count - 1]);

or

pointy.Insert(0, pointy.Last());

Full method being

public void ChangeList(List<double> arrayList)
        {
            arrayList.Insert(0, arrayList.Last());
            arrayList.RemoveAt(arrayList.Count - 1);
            arrayList.Reverse();
        }
like image 70
Dan Byström Avatar answered Dec 16 '25 16:12

Dan Byström



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!