【发布时间】:2020-06-28 23:53:33
【问题描述】:
我想按长度降序对短语的字符串列表进行排序,这样:
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.OrderedEnumerable2[System.String,System.Int32]' to type 'System.Collections.Generic.List1[System.String]' 的对象。”
我需要修复此代码,还是以完全不同的方式对其进行攻击?
【问题讨论】:
-
@Jawad - 和以前一样
IEnumerable as List<T>返回null所以这不起作用。 -
yes..
IEnumerable as List<T>不起作用,因为这也是将 IENumerable 转换为 List 的另一种方式......你不能这样做。您必须通过.ToList()方法将 IEnumerable 转换为 List。 (只是发布我删除的原始评论)
标签: c# sorting tstringlist