簡體   English   中英

C#排序小字母和大寫字母

[英]C# sorting strings small and capital letters

是否有標准功能允許我按以下方式對大寫字母和小寫字母進行排序,或者我應該實現自定義比較器:

student
students
Student
Students

例如:

using System;
using System.Collections.Generic;

namespace Dela.Mono.Examples
{
   public class HelloWorld
   {
      public static void Main(string[] args)
      {
         List<string> list = new List<string>();
         list.Add("student");
         list.Add("students");
         list.Add("Student");
         list.Add("Students");
         list.Sort();

         for (int i=0; i < list.Count; i++)
             Console.WriteLine(list[i]);
      }
   } 
}

它將字符串排序為:

student
Student
students
Students

如果我嘗試使用list.Sort(StringComparer.Ordinal) ,則排序如下:

Student
Students
student
students

你的意思是這些話嗎?

List<string> sort = new List<string>() { "student", "Students", "students", 
                                         "Student" };
List<string> custsort=sort.OrderByDescending(st => st[0]).ThenBy(s => s.Length)
                                                         .ToList();

第一個按第一個字符排序,然后按長度排序。 它根據我上面提到的模式匹配你建議的輸出,否則你將做一些自定義比較器

我相信你想把那些以小寫和大寫字母開頭的字符串分組,然后分別對它們進行排序。

你可以做:

list = list.Where(r => char.IsLower(r[0])).OrderBy(r => r)
      .Concat(list.Where(r => char.IsUpper(r[0])).OrderBy(r => r)).ToList();

首先選擇以小寫字母開頭的字符串,對它們進行排序,然后將它與以大寫字母開頭的字符串連接起來(對它們進行排序)。 所以你的代碼將是:

List<string> list = new List<string>();
list.Add("student");
list.Add("students");
list.Add("Student");
list.Add("Students");
list = list.Where(r => char.IsLower(r[0])).OrderBy(r => r)
      .Concat(list.Where(r => char.IsUpper(r[0])).OrderBy(r => r)).ToList();
for (int i = 0; i < list.Count; i++)
    Console.WriteLine(list[i]);

並輸出:

student
students
Student
Students

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM