Welcome to AspAdvice Sign in | Join | Help

Sort Generic List of T

Plenty of others have written about this so I'll keep it brief.  I needed to sort some objects based on a string property.  Some quick searching led me to this post which got me close to what I wanted.

 

My final code was this:

myThings.Sort(delegate(Thing x, Thing y) { return String.Compare(x.Name,y.Name); }); 

myThings is a List<Thing> collection.  String.Compare done in this fashion will sort them alphabetically - reverse its parameters to sort in reverse.

Sponsor
Published Sunday, June 17, 2007 1:12 AM by ssmith
Filed under:

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

# Interesting Finds: June 18, 2007

Monday, June 18, 2007 4:31 PM by Jason Haley

# re: Sort Generic List of T

Or just make your Thing class implement IComparable<Thing>, implementing the CompareTo method like this:

public int CompareTo(Thing other)

{

   return Name.CompareTo(other.Name);

}

This way you don't have to create an anonymous method each time you need to sort the list.

Monday, June 18, 2007 8:58 PM by SimoneB

# re: Sort Generic List of T

Good point, especially in cases where I have control over everything involved in my type (Thing), as in this case I do!  Thanks!

Monday, June 18, 2007 11:29 PM by ssmith

# How to sort a generic List<T>

After reading this post from Steven Smith I thought I should write something about it. Sorting a generic

Tuesday, June 19, 2007 8:13 PM by SimoneB's Blog

# re: Sort Generic List of T

Has anyone noticed this oddity?

Say I have a generic list of objects and I call Sort providing it with a routine that compares the object by a property they has which is ob type Long.

If the objects do indeed contain different long values then they are nicely sorted into Long order...but the oddity is:

If the objects all have the same Long value (say 0) then the result of calling Sort reverses the current order of the List?! This is bad as it just reodered my objects for no good reason. And incidentally if you call sort again they reverse once again back to their original order!

How do I stop this happening?

Stuart

Wednesday, June 27, 2007 5:44 AM by Stuart

Leave a Comment

(required) 
required 
(required) 
Enter the code you see below