2012-11-30 63 views
1

有没有一个标准功能,它可以让我以下列方式排序,大写和小写字母,或者我应该实现自定义比较:C#字符串进行排序小和大写字母

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 
+1

你需要定制的东西在这里。 – ryadavilli

+0

你想得到什么结果? – CR41G14

+0

@ryadavilli:我希望有更懒的解决方案! :) 不管怎么说,还是要谢谢你! – nenito

回答

2

你的意思是在这些线上由

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

第一个订单它的第一个字符,然后由长度的东西。 它匹配你建议的输出,然后根据我上面提到的模式,否则你会做一些自定义比较器

+0

谢谢!这是行得通的,但是您需要将OrderBy更正为OrderByDescending! – nenito

1

我相信你想要组合那些以小写和大写开头的字符串,然后分开排序。

你可以这样做:

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 
相关问题