简体   繁体   English

C#按索引对数组重新排序,甚至奇数降序

[英]C# Reordering array by index even ascending odd descending

I need to reorder an array by skipping one element each time, first taking the evenly indexed elements ascending, and then taking the oddly indexed elements in descending order. 我需要通过每次跳过一个元素来重新排序数组,首先使均匀索引的元素升序,然后按降序获取奇数索引的元素。

For example, say I have an array of double that is ordered like this: 例如,假设我有一个double数组,其顺序如下:

[0, 0.3, 0.7, 1.1, 1.5, 1.9, 2.3, 2.7, 3.1, 3.5, 3.9] [0,0.3,0.7,1.1,1.5,1.9,2.3,2.7,3.1,3.5,3.9]

I would like to have it ordered like this: 我想要这样订购:

[0, 0.7, 1.5, 2.3, 3.1, 3.9, 3.5, 2.7, 1.9, 1.1, 0.3] [0,0.7,1.5,2.3,3.1,3.9,3.5,2.7,1.9,1.1,0.3]

As you can see, I'm not interested in ordering by the values, but only the index of the elements. 如您所见,我对按值排序并不感兴趣,而仅对元素的索引感兴趣。 I can't find an overload of Array.Sort or IEnumerable<>.OrderBy that gives the index, so I can't seem to use that. 我找不到提供索引的Array.Sort或IEnumerable <>。OrderBy的重载,所以我似乎无法使用它。

I feel a bit ashamed to ask what seems like such a simple question, but I can't figure out how to do that elegantly. 我感到有点ham愧,问这样一个简单的问题,但我不知道如何优雅地做到这一点。 I can of course do it with a foreach loop and playing with the indexes, but I'm "translating" some Matlab code and this particular part is made with this elegant (albeit complex to understand if you're not used to that kind of things) one liner: 我当然可以通过foreach循环并使用索引来做到这一点,但是我正在“翻译”一些Matlab代码,并且这个特殊的部分是用这种优雅的(尽管很复杂,如果您不习惯这种类型的话就可以理解)东西)一线:

y = y([1:2:n 2 * floor(n / 2):-2:2],:); % n being the number of elements in the array y

This code will take every other element of the array: 此代码将采用数组的所有其他元素:

var firstHalf = a.Where((value, index) => index % 2 == 0);

A simple modification will get the other set: 一个简单的修改将得到另一个集合:

var secondHalf = a.Where((value, index) => index % 2 == 1).Reverse();

Then you can combine the two: 然后,您可以将两者结合起来:

var result = firstHalf.Concat(secondHalf);

You could get all the odd and even indexes using linq like so: 您可以使用linq获得所有奇数和偶数索引,如下所示:

double[] ar = new double[]{0, 0.3, 0.7, 1.1, 1.5, 1.9, 2.3, 2.7, 3.1, 3.5, 3.9};
var odds = ar.Where((val, index) => index % 2 != 0);
var evens = ar.Where((val, index) => index % 2 == 0);

then reverse the odds and combine the two 然后扭转几率,将两者结合

As elegance is subjective, let me suggest you this : 由于优雅是主观的,所以我建议您这样做:

double [] elements = {0, 0.3, 0.7, 1.1, 1.5, 1.9, 2.3, 2.7, 3.1, 3.5, 3.9};

double [] result = elements
             .Select((value, index) => new {Index = index, Value = value})
             .OrderBy(a => a.Index % 2)
             .ThenBy(a => (a.Index % 2 == 0 ? 1 : -1) * a.Value)
             .Select(a => a.Value).ToArray(); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM