如何按长度降序对字符串列表的内容进行排序?

时间:2020-06-28 23:53:33

标签: c# sorting tstringlist

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

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);

...但是最后一行无法编译,并且Intellisense建议我将其更改为:

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

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

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

2 个答案:

答案 0 :(得分:7)

使用此:

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

答案 1 :(得分:2)

List<T>类的定义是:

public class List<T> :  IEnumerable<T>,...

List<T> 类继承自IEnumerable<T>,其中OrderByDescending返回IOrderedEnumerable<out TElement>,该类也继承自IEnumerable<T>

IOrderedEnumerable接口的定义是:

public interface IOrderedEnumerable<out TElement> : IEnumerable<TElement>, IEnumerable

检查:

IEnumerable<string> enumerable1 = new List<string>{ "x","y"};
List<string> list1 = (List<string>)enumerable1; //valid

IEnumerable<string> enumerable2 =new  Collection<string>{ "x","y"};
List<string> list2 = (List<string>)enumerable2; //runtime error

每个List<T>Collection<T>都是IEnumerable<T>始终是事实。但是说每个IEnumerable<T>是一个List<T>

enter image description here

不会出现IOrderedEnumerable<out TElement>被强制转换为List的情况,因为它们不在同一层次结构中。

因此,正如@cee sharper所述,我们不得不调用ToList()扩展方法,以将IOrderedEnumerable<out TElement>转换为List<T>

List<string> list = new List{"x","xx","xxx"}.OrderByDescending(x => x.Length).ToList();