gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 01:07:04 25 4
gpt4 key购买 nike

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

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();

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

关于C# 排序字符串小写字母和大写字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13642068/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com