You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在VB.NET中获取排序后列表的索引?

VB.NET 获取排序后列表的原索引序列

针对你给出的List(Of Double),要在排序后获取对应的原索引,不能直接使用mList.Sort()(会修改原列表且丢失索引信息),可以通过将元素与原索引绑定后排序的方式实现:

实现步骤与代码

  1. 定义原列表(你已有的代码):
Dim mList As New List(Of Double)
mList.AddRange({3, 2, 5, 3, 6})
  1. 创建包含元素值和原索引的配对集合:
' 用LINQ将每个元素与它的原索引关联
Dim indexedList = mList.Select(Function(val, idx) New With {.Value = val, .Index = idx}).ToList()
  1. 对配对集合排序(按值升序,值相同时按原索引升序,匹配你需要的结果):
indexedList.Sort(Function(x, y)
                     ' 先比较元素值
                     Dim valComparison = x.Value.CompareTo(y.Value)
                     ' 值相同则比较原索引,保证顺序正确
                     If valComparison = 0 Then
                         Return x.Index.CompareTo(y.Index)
                     End If
                     Return valComparison
                 End Function)
  1. 提取排序后的原索引序列:
' 从排序后的配对集合中取出原索引,得到目标序列
Dim sortedIndices = indexedList.Select(Function(item) item.Index).ToList()

执行后,sortedIndices的值就是{1, 0, 3, 2, 4},完全符合你的需求。

内容的提问来源于stack exchange,提问作者Anas Ahmed

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 09:15:49