【问题标题】:C# sorting strings small and capital lettersC#对字符串排序大小写字母
【发布时间】:2012-11-18 11:42:35
【问题描述】:

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

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

【问题讨论】:

  • 你需要在这里定制一些东西。
  • 你希望结果是什么?
  • @ryadavilli:我希望有一些更懒惰的解决方案! :) 还是谢谢!
  • 你只关心第一个字母的大小写吗?如果后面的字母大写怎么办?

标签: c# string sorting case-sensitive


【解决方案1】:

你的意思是什么意思

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

第一个按第一个字符排序,然后按长度排序。 根据我上面提到的模式,它与您当时建议的输出相匹配,否则您将执行一些自定义比较器

【讨论】:

  • 谢谢!这是有效的,但您需要将 OrderBy 更正为 OrderByDescending!
【解决方案2】:

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

你可以这样做:

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

【讨论】:

    猜你喜欢
    • 2019-08-12
    • 1970-01-01
    • 2019-07-10
    • 1970-01-01
    • 1970-01-01
    • 2016-04-13
    • 1970-01-01
    • 2020-08-24
    • 1970-01-01
    相关资源
    最近更新 更多