c# - 尝试创建一种方法,按小写首字母升序排序句子,然后按大写首字母降序排序
问题描述
我正在尝试编写一个 C# 方法,该方法接受句子“The quick brown Fox jumped over the lazy Dog”,并按第一个字母升序对其进行排序,然后在末尾按降序对任何大写单词进行排序。结果应该是这样的......“棕色的狐狸狗很快就懒洋洋地跳了过去”。
我被困在如何将三个大写单词添加到空列表中。到目前为止,我的代码识别了大写的单词,但无法弄清楚如何将这些单词移动到空列表中。我尝试了几种方法,包括 .Add()。我可能会弄错语法。
我的逻辑是我将创建第二个包含大写单词的列表,对两个列表进行排序然后将它们连接起来。这是我在这里的第一篇文章,所以如果事情没有像他们应该的那样清楚,我提前道歉。对此的任何帮助都会很棒。谢谢
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
string words = "The quick brown Fox jumped over the lazy Dog.";
List<string> wordList = words.Split(' ').ToList();
List<string> upperList = new List<string>();
foreach (string word in wordList)
{
if (Char.IsUpper(word, 0))
{
Console.WriteLine(word);
}
}
Console.ReadLine();
}
}
}
解决方案
您可以使用 LINQ:
List<string> wordList = words.Split(' ').
OrderBy(word => char.IsUpper(word[0])).
ThenBy(word => word).ToList();
推荐阅读
- reactjs - 如何故意将 Web 服务器配置为返回 500
- node.js - renderer() 组件中的状态未更新
- javascript - 渲染 Firebase JSON 对象反应
- javascript - 浏览器:已经声明了标识符输入,但仅在 wordpress 上?
- java - 在没有库的情况下转换为 JSONObject 并返回 Kotlin
- google-apps-script - 使用应用程序脚本在 Big Query 中创建视图 | 错误:对 bigquery.tables.insert 的 API 调用失败并出现错误:缺少必需的参数(第 21 行
- c++ - 如何使用 strcmp 使循环结束循环
- angular - 如何将 metronic 的引导主题用于其他有角度的现有项目?
- java - 如何在java中使用预定义变量设置计数器
- c++ - 模板类在非参数化构造函数上抛出错误