C# 排序列表同时还返回原始索引位置? [英] C# Sort list while also returning the original index positions?
本文介绍了C# 排序列表同时还返回原始索引位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我对排序集合感兴趣,但也返回一个索引,该索引可用于映射到集合中的原始位置(排序之前).
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).
举个例子更清楚:
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[i] == 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.
下面是一些代码来演示原理:
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],但希望这对你来说已经足够了.
I think this gives A[idx[i]] = B[i], but that hopefully is good enough for you.
这篇关于C# 排序列表同时还返回原始索引位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文