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

  • Thread starter Thread starter Ethan Strauss
  • Start date Start date
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
 
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?
 
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".
 
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
 
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
 
Back
Top