如何实现双列表同步排序:按D_x降序重排ID_x对应元素?
同步排序两个关联列表的实现方法
针对你需要将D_x降序排序并同步调整ID_x元素位置的需求,以下是两种实用的C#实现方案:
方案一:使用LINQ Zip配对排序(简洁推荐)
通过Zip方法将两个列表的对应元素配对,排序后再拆分回两个列表,代码简洁易读:
using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { List<string> ID_x = new List<string>() { "ID2", "ID3", "ID2", "ID1", "ID4", "ID1", }; List<double> D_x = new List<double>() { 3.5, 8.8, 1.1, 2.3, 3.5, 6.8, }; // 配对元素并按D值降序排序 var sortedPairs = ID_x.Zip(D_x, (id, d) => new { Id = id, Value = d }) .OrderByDescending(pair => pair.Value) .ToList(); // 拆分回两个新列表 List<string> newID_x = sortedPairs.Select(p => p.Id).ToList(); List<double> newD_x = sortedPairs.Select(p => p.Value).ToList(); // 输出结果验证 Console.WriteLine("new ID_x list: " + string.Join(", ", newID_x)); Console.WriteLine("new D_x list: " + string.Join(", ", newD_x)); } }
运行后会得到你需要的结果:
new ID_x list: ID3, ID1, ID2, ID4, ID1, ID2
new D_x list: 8.8, 6.8, 3.5, 3.5, 2.3, 1.1
方案二:通过索引排序(无需LINQ)
如果项目中限制使用LINQ,可以通过创建索引列表,按D_x的值排序索引,再根据排序后的索引重构列表:
using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { List<string> ID_x = new List<string>() { "ID2", "ID3", "ID2", "ID1", "ID4", "ID1", }; List<double> D_x = new List<double>() { 3.5, 8.8, 1.1, 2.3, 3.5, 6.8, }; // 创建索引列表 List<int> indices = Enumerable.Range(0, D_x.Count).ToList(); // 按D_x对应的值降序排序索引 indices.Sort((a, b) => D_x[b].CompareTo(D_x[a])); // 根据排序后的索引构建新列表 List<string> newID_x = new List<string>(); List<double> newD_x = new List<double>(); foreach (int i in indices) { newID_x.Add(ID_x[i]); newD_x.Add(D_x[i]); } // 输出结果验证 Console.WriteLine("new ID_x list: " + string.Join(", ", newID_x)); Console.WriteLine("new D_x list: " + string.Join(", ", newD_x)); } }
注意事项
- 确保两个列表初始长度一致,否则
Zip方法会以较短列表的长度为准,忽略较长列表的多余元素。 - 如果需要原地修改原列表而非创建新列表,可以在排序索引后,先创建原列表的副本,再按索引顺序重新赋值原列表元素。
内容的提问来源于stack exchange,提问作者JMLC
相关产品推荐
相关产品推荐

