sort list

  • Thread starter Thread starter Tem
  • Start date Start date
T

Tem

What's a good way to sort a List<string> by the length of the strings from
longest to shortest. in c# 3

"aaaaaa"
"aaaaaaaaaa"
"aaa"

becomes
"aaaaaaaaaa"
"aaaaaa"
"aaa"


Thx
Tem
 
Tem said:
What's a good way to sort a List<string> by the length of the strings
from longest to shortest. in c# 3

"aaaaaa"
"aaaaaaaaaa"
"aaa"

becomes
"aaaaaaaaaa"
"aaaaaa"
"aaa"

My suggestion:

lst.Sort((s1, s2) => s2.Length - s1.Length);

Arne
 
If you have C# 3, you might also have access to .NET 3.5 and LINQ;
slightly different, because LINQ creates a *new* set of data (rather
than an in-place sort), but another quite clear way of writing this
would be:

List<string> newList = oldList.OrderByDescending(s =>
s.Length).ToList();

The in-place sort (as per Arne) is quite possible more efficient, but
it depends what you need. As an aside, LINQ performs a "balanced"
side, meaning that if there are two strings length 4 (say), they will
remain in their original order, where-as List<T>.Sort makes no
guarantee what order they will end in. In reality this is very rarely
a concern ;-p
 
The in-place sort (as per Arne) is quite possible more efficient, but
it depends what you need. As an aside, LINQ performs a "balanced"
side, meaning that if there are two strings length 4 (say), they will
remain in their original order, where-as List<T>.Sort makes no
guarantee what order they will end in. In reality this is very rarely
a concern ;-p

Just on a terminology note, I don't think I've heard sorts referred to
as "balanced" before, but "stable" (vs unstable). Balanced may well be
correct as well, but I thought I'd throw "stable" into the mix in case
it's more familiar :)

Jon
 
Lol - sorry Jon, you are absolutely correct! I should get another
coffee in me: I seem to be unbalanced / unstable this am [take your
pick] ;-p

Marc
 
Marc said:
If you have C# 3, you might also have access to .NET 3.5 and LINQ;
slightly different, because LINQ creates a *new* set of data (rather
than an in-place sort), but another quite clear way of writing this
would be:

List<string> newList = oldList.OrderByDescending(s =>
s.Length).ToList();

The in-place sort (as per Arne) is quite possible more efficient, but
it depends what you need.

If you need a new set of data, then nothing prevents you
from making a copy of the list and sort that in-place.

It is still valid to write code without using LINQ !

:-)

Arne
 

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

Back
Top