首页 > 解决方案 > 尝试创建一种方法,按小写首字母升序排序句子,然后按大写首字母降序排序

问题描述

我正在尝试编写一个 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();
        }
    }
}

标签: c#list

解决方案


您可以使用 LINQ:

List<string> wordList = words.Split(' ').
    OrderBy(word => char.IsUpper(word[0])).
    ThenBy(word => word).ToList();

在线演示:https ://dotnetfiddle.net/f59eUt


推荐阅读