Sort (strings)

  • Thread starter Thread starter csharpula csharp
  • Start date Start date
C

csharpula csharp

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!
 
In 2.0 you can use the List<T>.Sort(Comparison<T>) overload:

List<string> list = 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
 
Marc said:
In 2.0 you can use the List<T>.Sort(Comparison<T>) overload:
foreach (string s in list.OrderBy(s=>s.Length))
{
Console.WriteLine(s);
}

Hi Marc,

Am I correct in assuming that if you have multiple strings with the
same length, there is no guarantee as to the order of strings with the
same length?

In other words, if I have the strings:

ab
abcde
abc
abccd
abdc

Will abccd be sorted before abcde every time? Or does it depend on
their original order in the list?

Thanks,

Chris
 
You've quoted from 2 different examples there, and the behavior is
different... taking them separately:
In 2.0 you can use the List<T>.Sort(Comparison<T>) overload:

List<T> performs an unbalanced sort; there is no specific order to things
that match. You can add extra sorts, but short of introducing a row-index
(separately) there is no way of doing a balanced (matches listed in original
order) sort.
foreach (string s in list.OrderBy(s=>s.Length))

This is LINQ-to-Objects, which performs balanced sorts; so the order will
depend on the original order in the list. Obviously, if the LINQ query is
going to a different provider (LINQ-to-Foo), then it will be
provider-specific. If you want it sorted alphabetically, then you can append
a .ThenBy(), or use the alternative query langauge syntax.

Marc
 

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

Similar Threads

Table Format to Hold Data 16
Enum To String 14
How to sort List<...> -- created using LinQ? 11
Remove characters from string 2
xml vs xsd 2
Compare (List<string> 6
Question about sorting 5
copy rows to next sheet 3

Back
Top