我是一个编程的初学者,还在学习,我有两个数组,一个用于汽车,第二个用于汽车速度

string[] cars = {"Volvo", "BMW","Ford", "Mazda"};

Int[] speeds = {150,130,200,110}

所以沃尔沃的速度是150,宝马的速度是130,福特的速度是300,等等

在C#中有没有一种方法可以按照速度从最高到最低重新排列数组,从而使数组如下所示

String[] cars = {"ford","volvo","bmw","mazda"};

Int[] speeds = {300,150,130,110};

推荐答案

一种简洁的方法是将两个数组"压缩"到一个元组数组中,按速度对元组进行排序,然后将元组拆分为两个数组:

var tuples = cars.Zip(speeds, (car, speed) => (car, speed))
    .OrderByDescending(tuple => tuple.speed)
    .ToList();
string[] sortedCars = tuples.Select(tuple => tuple.car).ToArray();
int[] sortedSpeeds = tuples.Select(tuple => tuple.speed).ToArray();

通过向Zip添加更多调用,您可以对三个或更多数组进行排序:

var tuples = cars.Zip(speeds, (car, speed) => (car, speed))
    .Zip(colors, (tuple, color) => (tuple.car, tuple.speed, color))
    // .Zip(weights, (tuple, weight) => (tuple.car, tuple.speed, tuple.color, weight))
    .OrderByDescending(tuple => tuple.speed)
    .ToList();
string[] sortedCars = tuples.Select(tuple => tuple.car).ToArray();
int[] sortedSpeeds = tuples.Select(tuple => tuple.speed).ToArray();
string[] sortedColors = tuples.Select(tuple => tuple.color).ToArray();
// int[] sortedWeights = tuples.Select(tuple => tuple.weight).ToArray();    

但在这一点上,正如Guru Stron所指出的,您真的应该考虑引入一个Car类,而不是使用单独的array.

Csharp相关问答推荐

ß != ss与ICU进行不区分大小写的比较

为什么使用DXGI输出复制和Direct 3D时捕获的图像数据全为零?

错误NU 1301:无法加载源的服务索引

应该使用哪一个?"_counter += 1 OR互锁增量(ref_counter)"""

如何在Reflection. Emit中使用具有运行时定义的类型参数的泛型类型

使用Audit.EntityFramework,我如何将外键的值设置为相关实体上的属性?

不带身份的Blazor服务器.Net 8 Cookie身份验证

尽管保证密钥不同,但已添加相同密钥的项(&Q;)

当用户右键单击文本框并单击粘贴时触发什么事件?

try 在.Net核心身份注册页面中使用AJAX,但没有成功..NET Core 5.0 Razor页面应用程序

将类移动到新命名空间后更新RavenDB Raven-Clr-Type

无法使用[FromForm]发送带有图像和JSON的多部分请求

在C#.NET项目中启动时,如何等待提升的PowerShell进程退出?

如何实现有条件的自定义Json转换器隐藏属性

EF Core:如何对关系属性进行建模?

在.NET8中如何反序列化为私有字段?

KeyDown从我的文本框中删除输入,如何停止?

无法向Unity注册Microsoft Logger

C#;AvaloniaUI;MVVM;当另一个窗口上的按钮被单击时,如何更新视图图像源?

使用postman 测试配置了身份的.NET 6应用程序