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.List
1[System.String]'."
Do I need a fix to this code, or to attack it in a completely different way?
Use this:
slPhrasesFoundInBothDocs =
slPhrasesFoundInBothDocs
.OrderByDescending(x => x.Length)
.ToList();