Search code examples
c#sortingtstringlist

How can I sort the contents of a string list by length descending?


I want to sort a string list of phrases by length, descending, so that this:

Rory Gallagher
Rod D'Ath
Gerry McAvoy
Lou Martin

would end up as:

Rory Gallagher
Gerry McAvoy
Lou Martin
Rod D'Ath

I wanted to try this first:

List<string> slPhrasesFoundInBothDocs;
. . . // populate slPhrasesFoundInBothDocs
slPhrasesFoundInBothDocs = slPhrasesFoundInBothDocs.OrderByDescending(x => x.Length);

...but the last line wouldn't compile, and intellisense suggested that I change it to:

slPhrasesFoundInBothDocs = (List<string>)slPhrasesFoundInBothDocs.OrderByDescending(x => x.Length);

...which I did. It compiles, but throws a runtime exception, namely, "Unable to cast object of type 'System.Linq.OrderedEnumerable2[System.String,System.Int32]' to type 'System.Collections.Generic.List1[System.String]'."

Do I need a fix to this code, or to attack it in a completely different way?


Solution

  • Use this:

    slPhrasesFoundInBothDocs =
        slPhrasesFoundInBothDocs
            .OrderByDescending(x => x.Length)
            .ToList();