Oliver Barnum
Oliver Barnum

Reputation: 75

How does one sort a list of integers largest to smallest

I'm building a simple program that creates a bunch of scattered trees on the screen in C#. I am still relatively new to C# so bear with me. My program creates the trees but some of the images end up on top of each other because the trees are drawn in a seemingly random order.

I have a list of the tree objects and I was wondering how one goes about sorting this list by the trees' Y value (treeObject.position.Y), that way when I call every trees' draw methods in a for loop it will draw the ones furthest back (smallest Y) first. I tried hard coding it but It became too cumbersome.

Full Code is given here: http://pastebin.com/5G6aecLm

Upvotes: 0

Views: 1558

Answers (3)

Dummy01
Dummy01

Reputation: 1995

If I understood your problem, there are many ways to do it, here is just one:

Assuming that your list is of type List<TreeObject>:

using System.Linq;

var q = yourList.AsEnumerable<TreeObject>().OrderBy(obj => obj.position.Y);

Then just loop q to get your objects in the correct order.

Upvotes: 1

DanRedux
DanRedux

Reputation: 9349

If you're using a drawing engine capable of 3D, just use a ortho view of the world. You'll see no difference, but you'll be able to use z to control depth (z=-y will then have the desired effect), as well as being able to scale, rotate, and morph your 2D sprites efficiently.

Upvotes: 0

Dr.Kameleon
Dr.Kameleon

Reputation: 22820

Using some sort algorithm, preferably : QuickSort

Upvotes: 2

Related Questions