C#排序字符串小写和大写字母

是否有标准function允许我按以下方式对大写字母和小写字母进行排序,或者我应该实现自定义比较器:

student students Student Students 

例如:

 using System; using System.Collections.Generic; namespace Dela.Mono.Examples { public class HelloWorld { public static void Main(string[] args) { List list = new List(); 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 sort = new List() { "student", "Students", "students", "Student" }; List 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 list = new List(); 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