多数组排序在C# [英] Multi array sort in C#

查看:111
本文介绍了多数组排序在C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的数组:

int[] a = {5, 2, 3}; 
int[] b = {4, 1, 2}; 
string[] c = {"John", "Peter", "Max"};

我需要,以便它们得到相应排序,对,比如说,但在与其他两个阵列关系的值,第二阵列(二[])进行排序。例如, 1 将是第一位的,因为它是最低的数字,自 1 B [] 涉及到 2 A [] 彼得 C [] ,那么就意味着 2 彼得也将移动到第一个排序位置了。这同样适用于其它两列;注意:

I need to sort the values ​​of, say, the second array (b[]), but in relation with the other two arrays, so that they get sorted accordingly. For example, 1 will come first as it's the lowest number, and since 1 in b[] relates to 2 in a[] and "Peter" in c[], then it means that 2 and "peter" will also move to the first sort position too. The same goes for the other two columns; observe:

int[] a = {2, 3, 5}; 
int[] b = {1, 2, 4}; 
string[] c = {"Peter", "Max", "John"};

我将如何做到这一点?

How would I do this?

推荐答案

我想我明白你在说什么。要排序的数组 A ,并根据 C $ C>。

I think I understand what you are saying. You want to sort array a and c based on the values of b.

您可以按使用的Array.Sort 另一个阵列,它可以让您指定的其他数组例如键的数组:

You can sort an array by another array using Array.Sort which lets you specify another array for keys for example:

int[] a = { 5, 2, 3 }; 
int[] b = { 4, 1, 2 };
string[] c = { "John", "Peter", "Max" };

Array.Sort(b.ToArray(), c);
Array.Sort(b.ToArray(), a);
Array.Sort(b);
Console.WriteLine(string.Join(", ", a));
Console.WriteLine(string.Join(", ", b));
Console.WriteLine(string.Join(", ", c));

这将输出的预期值。注意,我们使用的ToArray 以创建数组的副本时,通过按键排序,这是因为的Array.Sort 这两个排序他们键和值,这是我们不想要的。我们不走到最后排序键( B 在这种情况下)。

This will output your expected values. Note that we use ToArray to create a copy of the arrays when sorting by key, that's because Array.Sort sorts both they keys and the values, which we don't want. We don't sort the Keys (b in this case) till the end.

这就是我们如何解决立即解决问题。不过,从收集到的意见,你试图表格数据进行排序。当你的数据有一定的结构来呢,说是这样的:

That's how we solve your immediate problem. However, gathered from the comments, you are trying to sort tabular data. When your data has some structure to it, say like this:

public class Item
{
    public int A { get; set; }
    public int B { get; set; }
    public string C { get; set; }
}

它得到的很多的更容易。

var items = new[]
{
    new Item {A = 5, B = 4, C = "John"},
    new Item {A = 2, B = 1, C = "Peter"},
    new Item {A = 3, B = 2, C = "Max"},
};
var sortedItems = items.OrderBy(i => i.B).ToArray();

此使用 LINQ ,该是完美的你正在尝试做的。

This uses LINQ, which is perfect for what you are trying to do.

这篇关于多数组排序在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆