sort list

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

    #1

    sort list

    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

  • =?ISO-8859-1?Q?Arne_Vajh=F8j?=

    #2
    Re: sort list

    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

    Comment

    • Marc Gravell

      #3
      Re: sort list

      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

      Comment

      • =?ISO-8859-1?Q?Arne_Vajh=F8j?=

        #4
        Re: sort list

        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<stringnewL ist = oldList.OrderBy Descending(s =>
        s.Length).ToLis t();
        >
        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

        Comment

        Working...