3 Replies - 629 Views - Last Post: 05 April 2011 - 09:08 AM Rate Topic: -----

#1 alexdgr8r   User is offline

  • New D.I.C Head

Reputation: 5
  • View blog
  • Posts: 4
  • Joined: 03-September 10

How do I sort a list made up of a certain Class?

Posted 04 April 2011 - 03:49 PM

I'm developing a game where I want the images to be drawn in order from their Y position. I have a class called Character in which I give them a Position value.
public static Vector2 position

Every time a new Character is spawned I want to add it to a list so that way I can redraw them when necessary. In order to keep them from looking all messed up and overlapping each other, I want to draw them in order of the position.Y. So I need to sort the list of Characters by their Y value. How do I go about this? I am totally confused on the whole Sort method and its inter workings.

Is This A Good Question/Topic? 0
  • +

Replies To: How do I sort a list made up of a certain Class?

#2 Curtis Rutland   User is offline

  • (╯□)╯︵ (~ .o.)~
  • member icon


Reputation: 5106
  • View blog
  • Posts: 9,283
  • Joined: 08-June 10

Re: How do I sort a list made up of a certain Class?

Posted 04 April 2011 - 04:00 PM

If you're using .NET 3.5 or higher, you can use LINQ to sort your array or list.

Assuming your List is named list:

list = list.OrderBy(x => x.position.Y).ToList();


You have to add using System.Linq; to the top.
Was This Post Helpful? 2
  • +
  • -

#3 AdamSpeight2008   User is offline

  • MrCupOfT
  • member icon

Reputation: 2298
  • View blog
  • Posts: 9,535
  • Joined: 29-May 08

Re: How do I sort a list made up of a certain Class?

Posted 04 April 2011 - 04:06 PM

Or you could Implement IComparer.Compare
Custom Sorting Tutorial(vb.net)

This post has been edited by AdamSpeight2008: 04 April 2011 - 04:07 PM

Was This Post Helpful? 2
  • +
  • -

#4 lordofduct   User is offline

  • I'm a cheeseburger
  • member icon


Reputation: 2668
  • View blog
  • Posts: 4,786
  • Joined: 24-September 10

Re: How do I sort a list made up of a certain Class?

Posted 05 April 2011 - 09:08 AM

Or create a method that meets the delegate definition of System.Comparison<T>

http://msdn.microsof...y/tfakywbh.aspx



All are valid options. Linq being more meta, IComparer being more object-oriented, and Comparison<T> being more functional.

And people say the .Net framework is for pansies who don't know how to really code... blargh, it's just useful damn it!

This post has been edited by lordofduct: 05 April 2011 - 09:10 AM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1