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

Sort (strings)

P: n/a


Hello,
What is the best way to sort strings by lentgh in .NET 2.o
?

What is the best way to implement it?
Thank u!

*** Sent via Developersdex http://www.developersdex.com ***
Jul 6 '08 #1
Share this Question
Share on Google+
1 Reply


P: n/a
In 2.0 you can use the List<T>.Sort(Comparison<T>) overload:

List<stringlist = new List<string>();
list.Add("abc");
list.Add("abcde");
list.Add("ab");

list.Sort(delegate(string x, string y)
{ return x.Length.CompareTo(y.Length); }
);

foreach (string s in list)
{
Console.WriteLine(s);
}

The alternative would be to write a class that implements
IComparer<string- but the above is a lot easier ;-p
For reference, 3.5 (and LINQ) has a lot of support for ordering based
on projections (such as s =s.Length) - but if you have a C# 3
compiler you can still use this with .NET 2.0 via LINQBridge - then it
is as simple as:

foreach (string s in list.OrderBy(s=>s.Length))
{
Console.WriteLine(s);
}

http://www.albahari.com/nutshell/linqbridge.html

Marc
Jul 6 '08 #2

This discussion thread is closed

Replies have been disabled for this discussion.