Page view counter

Sorting a List<t> (What was I thinking??)

This entry updated after a night's sleep and the return of my cerebral cortex.

In one of my earlier entries you'll find something approximating this bit of nonsense…

public string DoSort(List<string> words)
{
List<string> temp = words.Sort(); // No, but thanks for playing.
return temp
}

Replace with

words.Sort();   // sorts list in place.

 

iStock_BoyWithBrainXSmall

For those of you who commented on my earlier attempt to explain how this would compile I can only tell you that I carefully tested it, but must have been sleep walking. I have a section in both of my books on C# that clearly says I was wrong, I have no idea what brain malfunction caused this, but I find that when this kind of thing happens the best thing is to take a nice long bath and throw the radio in.

 

 

 

-j

Published Sunday, December 14, 2008 8:56 AM by jesseliberty
Filed under:

Comments

# re: Sorting a List<t>

Wouldn't this not compile? Should throw a compile error when trying to assign a method that returns void to an object?

Sunday, December 14, 2008 3:46 PM by spo81rty

# re: Sorting a List<t>

Seems like you still don't quite understand this -- you say Sort both returns void and returns a copy of the sorted list.  Which is it?

Sunday, December 14, 2008 8:38 PM by maxchristian

# 2008 December 15 - Links for today &laquo; My (almost) Daily Links

Pingback from  2008 December 15 - Links for today &laquo; My (almost) Daily Links

# re: Sorting a List<t>

Is this what you were looking for?

public List<string> Sort(List<string> words) {

   return words.OrderBy(w => w).ToList();

}

or

public IEnumerable<string> Sort(IEnumerable<string> words) {

   return words.OrderBy(w => w);

}

Monday, December 15, 2008 8:32 AM by joechung

# re: Sorting a List<t> (What was I thinking??)

I have no excuse. My cereal doth taste of wormwood.

Monday, December 15, 2008 5:29 PM by jesseliberty