Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
362 views
in Technique[技术] by (71.8m points)

c# - How to sort two arrays by same index?

I have 2 arrays. I want to sort them by same index number. For example I have these:

int[] a = {120, 60, 50, 40, 30, 20};
int[] b = {12, 29, 37, 85, 63, 11};

Array.Sort(b); // Now, b is -> b = {11, 12, 29, 37, 63, 85}

I want to sort a by b's index -> a = {20, 120, 60, 50, 30, 40}

If I have also string array c -> c = {"b", "u", "r", "s", "a", "1"}

I want to sort c by b's index -> c = {"1", "b", "u", "r", "a", "s"}

How can I do this? Thanks in advance, Regards.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use Array.Sort<TKey, TValue>(TKey[] keys, TValue[] items) that accepts two input arrays, one is the array of keys, the other is the array of items to sort using those keys. Here, for you, b is your keys and a is your items.

Thus:

Array.Sort(b, a);

will use the keys of b to sort the items of a.

I want to sort c by b's index -> c = {"1", "b", "u", "r", "a", "s"}

Not clear exactly what you mean. At the same time as you sort a using b? If so, it's easy as we can still use the above. Zip a and c into a single array of Tuple<int, string>.

var d = a.Zip(c, (x, y) => Tuple.Create(x, y)).ToArray();

Then:

Array.Sort(b, d);

as above. Then extract the pieces:

a = d.Select(z => z.Item1).ToArray();
c = d.Select(z => z.Item2).ToArray();

Alternatively, if you need to sort a lot of arrays using the same set of keys:

int[] indexes = Enumerable.Range(0, b.Length).ToArray();
Array.Sort(b, indexes);

Now you can use indexes to sort all the arrays you need. For example:

a = indexes.Select(index => a[index]).ToArray();
c = indexes.Select(index => c[index]).ToArray();

etc. as needed.

Possibly some minor coding errors here. No compiler handy.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...