C# —— Sort排序

Array.Sort(ints);// 默认的排序方式 正序排序

cs 复制代码
int[] ints = { 1, 2, 3, 89, 20, 100 };
Console.Write(string.Join(",", ints));

参数1 是排序的数组,参数2 是函数 函数的两个参数 是数组的两个元素,

当返回x-y 正序排序

cs 复制代码
Array.Sort(ints, (x, y) => x - y);// 正序排序
Console.Write(string.Join(",", ints));

当返回y-x 正序排序

cs 复制代码
Array.Sort(ints, (x, y) => y - x);// 倒序排序
Console.WriteLine(string.Join(",", ints));

数组的元素是字符串 字符串也可以进行比较

因为字符串不能使用x-y这种方式进行比较

使用 CaseInsensitiveComparer.Default.Compare 对数字 字符串 汉字都可以进行对比

return CaseInsensitiveComparer.Default.Compare(x, y); // 正序排序

cs 复制代码
string[] strings = { "ad", "啊", "d", "ac", "9", "1", "中" };
Array.Sort(strings, (x, y) =>
{
    return CaseInsensitiveComparer.Default.Compare(y, x);// 倒序排序
});
Console.WriteLine(string.Join(",", strings));

实例:

cs 复制代码
string[] pukes = { "大王", "3", "8", "10", "J", "小王", "2" };

string[] leve1 = { "大王", "小王", "2", "A", "K", "Q", "J", "10", "9", "8", "7", "6", "5", "4", "3" };

Array.Sort(pukes, (x, y) =>
{
    // 将x和y转换对应的数字level数组的数字
    int levex = Array.IndexOf(leve1, x);// 获取原数组x 在leve1数组的索引值
    int levay = Array.IndexOf(leve1, y);// 获取y在leve1数组的索引值

    return levex - levay;
});

Console.WriteLine(string.Join(",", pukes));
相关推荐
历程里程碑3 分钟前
C++ 7vector:动态数组的终极指南
java·c语言·开发语言·数据结构·c++·算法
czhc11400756633 分钟前
c# 1213
开发语言·数据库·c#
sin_hielo9 分钟前
leetcode 2147
数据结构·算法·leetcode
萌>__<新22 分钟前
力扣打卡每日一题——缺失的第一个正数
数据结构·算法·leetcode
xiaoid37 分钟前
C#向jave平台的API接口推送
c#·post·webapi
重生之后端学习40 分钟前
238. 除自身以外数组的乘积
java·数据结构·算法·leetcode·职场和发展·哈希算法
Bruce_kaizy1 小时前
C++树形数据结构————树状数组、线段树中“逆序对”的问题
开发语言·数据结构·c++
FMRbpm1 小时前
用栈实现队列
数据结构·c++·新手入门
一韦以航.2 小时前
C【指针】详解(上)
c语言·数据结构·c++·算法
小猪快跑爱摄影2 小时前
【AutoCad 2025】【C#】零基础教程(三)——获取选中的 Entity 插件 =》 初识 Entity 派生类
c#·autocad