Sort (strings)

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • csharpula csharp

    Sort (strings)



    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 ***
  • Marc Gravell

    #2
    Re: Sort (strings)

    In 2.0 you can use the List<T>.Sort(Co mparison<T>) overload:

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

    list.Sort(deleg ate(string x, string y)
    { return x.Length.Compar eTo(y.Length); }
    );

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

    The alternative would be to write a class that implements
    IComparer<strin g- 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.WriteLi ne(s);
    }



    Marc

    Comment

    Working...