c# - 如何按长度降序对字符串列表的内容进行排序?
问题描述
我想按长度降序对短语的字符串列表进行排序,以便:
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.List
1[System.String]' 的对象。 ”
我需要修复此代码,还是以完全不同的方式对其进行攻击?
解决方案
用这个:
slPhrasesFoundInBothDocs =
slPhrasesFoundInBothDocs
.OrderByDescending(x => x.Length)
.ToList();
推荐阅读
- node.js - node 和 express 中 res.json() 的问题
- c# - C# 计算错误
- python - 您如何计算文本文件中的两个单独的行并断言它们彼此相等?
- java - 仅 ANTLR 匹配声明
- javascript - Surveyjs 选择随机排序,除了一些值
- c# - 如何在运行应用程序时将进程列入黑名单/白名单(C#)
- javascript - 我应该使用什么事件来关闭 Electron 应用程序中的客户端 websocket?
- java - 操作栏图标未更新
- angular - 清除数组时使用 Dialog 回调导致错误
- wordpress - 在网站上使用 yoast 插件后卸载