首页 > 解决方案 > 如何按长度降序对字符串列表的内容进行排序?

问题描述

我想按长度降序对短语的字符串列表进行排序,以便:

Rory Gallagher
Rod D'Ath
Gerry McAvoy
Lou Martin

最终会变成:

Rory Gallagher
Gerry McAvoy
Lou Martin
Rod D'Ath

我想先试试这个:

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

...但最后一行无法编译,并且智能感知建议我将其更改为:

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

...我做到了。它会编译,但会引发运行时异常,即“无法转换类型为 'System.Linq.OrderedEnumerable 2[System.String,System.Int32]' to type 'System.Collections.Generic.List1[System.String]' 的对象。

我需要修复此代码,还是以完全不同的方式对其进行攻击?

标签: c#sortingtstringlist

解决方案


用这个:

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

推荐阅读