Difference between List<T>.Sort() and List<T>OrderBy()

E

Ethan Strauss

Hi,
What is the difference between List<T>.Sort() and List<T>OrderBy()?
They seem to do essentially the same thing with different syntax. I know
that they have different signatures and Sort sorts the present list while
OrderBy returns a new list, but it seems that the actual sorting is really
the same. Is there any significant difference? Would either one be prefered?
Thanks,
Ethan
 
H

Harlan Messinger

Ethan said:
Hi,
What is the difference between List<T>.Sort() and List<T>OrderBy()?
They seem to do essentially the same thing with different syntax. I know
that they have different signatures and Sort sorts the present list while
OrderBy returns a new list, but it seems that the actual sorting is really
the same. Is there any significant difference? Would either one be prefered?

"... and Sort sorts the present list while OrderBy returns a new list,
....." Do you not see the difference between reordering a list and
leaving it untouched as a significant one? Is it less significant than
the fact that the second statement in

string x = "Hello";
string y = x.ToUpper();

leaves x unchanged?
 
M

Martin Honnen

Ethan said:
What is the difference between List<T>.Sort() and List<T>OrderBy()?
They seem to do essentially the same thing with different syntax. I know
that they have different signatures and Sort sorts the present list while
OrderBy returns a new list, but it seems that the actual sorting is really
the same. Is there any significant difference? Would either one be prefered?

The Sort method exists since .NET 2.0, the OrderBy method is part of
LINQ so it only exists since .NET 3.5.

Another difference is that Sort() "performs an unstable sort" while
OrderBy "performs a stable sort; that is, if the keys of two elements
are equal, the order of the elements is preserved".
 
H

Helmut Woess

Am Mon, 19 Apr 2010 19:14:03 +0200 schrieb Martin Honnen:
....
Another difference is that Sort() "performs an unstable sort" while
OrderBy "performs a stable sort; that is, if the keys of two elements
are equal, the order of the elements is preserved".

.... which is sometimes very important. I didn't know that. Thanks for the
info!

Helmut
 
E

Ethan Strauss

Thanks for the replies. It sounds like I can choose based mostly on if I want
to sort in place or if I prefer a new list.
The stability thing is interesting. I think I mostly don't care, but I had
never really considered that a sot could reorder items with the same value. I
am sure that will matter at some point.
Thanks!
Ethan
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top