By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
455,459 Members | 1,472 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 455,459 IT Pros & Developers. It's quick & easy.

sort list

P: n/a
Tem
What's a good way to sort a List<stringby the length of the strings from
longest to shortest. in c# 3

"aaaaaa"
"aaaaaaaaaa"
"aaa"

becomes
"aaaaaaaaaa"
"aaaaaa"
"aaa"
Thx
Tem

Jul 13 '08 #1
Share this Question
Share on Google+
3 Replies


P: n/a
Tem wrote:
What's a good way to sort a List<stringby 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
Jul 13 '08 #2

P: n/a
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
Jul 13 '08 #3

P: n/a
Marc Gravell wrote:
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<stringnewList = 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
Jul 13 '08 #4

This discussion thread is closed

Replies have been disabled for this discussion.