C#排序列表,同时也返回原来的索引位置? [英] C# Sort list while also returning the original index positions?
问题描述
我感兴趣的排序的集合,但也返回其可以用于映射到集合中(在排序之前)原来的位置的索引。
I'm interested in sorting a collection, but also returning an index which can be used to map to the original position in the collection (before the sort).
让我举一个例子来更清楚:
Let me give an example to be more clear:
List<int> A = new List<int>(){3,2,1};
List<int> B;
List<int> idx;
Sort(A,out B,out idx);
在其中:
A = [3,2,1]
B = [1,2,3]
idx = [2,1,0]
使A,B之间的关系,IDX是:
So that the relationship between A,B,idx is:
A [1] == B〔IDX [I]]
,其中i = 0 ... 2
A[i] == B[ idx[i] ]
, for i = 0...2
请问C#/。NET有任何内置的机制,使这个容易实现?
Does C#/.Net have any built in mechanism to make this easy to implement?
感谢。
推荐答案
这是可以做到很容易地使用LINQ。
It can be done quite easily using Linq.
- 您的列表转换为对一个新的列表(对象,对象的原始索引)。
- 新的列表排序由一对中的第一项
- 提取排序列表和原来的指数。
- Convert your list into a new list of pairs (object, original index of object).
- Sort the new list by the first item in the pair
- Extract the sorted list and the original indices.
下面是一些code证明一个道理:
Here's some code to demonstrate the principle:
List<int> A = new List<int>() { 3, 2, 1 };
var sorted = A
.Select((x, i) => new KeyValuePair<int, int>(x, i))
.OrderBy(x => x.Key)
.ToList();
List<int> B = sorted.Select(x => x.Key).ToList();
List<int> idx = sorted.Select(x => x.Value).ToList();
我觉得这给A [IDX [I] = B [我],但希望是配不上你。
I think this gives A[idx[i]] = B[i], but that hopefully is good enough for you.
这篇关于C#排序列表,同时也返回原来的索引位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!