数组排序带索引

匿名 (未验证) 提交于 2019-12-02 23:55:01

想到了两种方法来实现,分别利用了List.Sort()和Dictionary.OrderBy()方法,代码如下:

 1            int[] arrInt = new int[] { 11, 38, 12, 9, 234, 24, 441, 24, 45, 35 };  2   3             //List.Sort()  4             List<int> lstOrg = new List<int>(), lstSort = new List<int>();  5             lstOrg.AddRange(arrInt);  6             lstSort.AddRange(arrInt);  7             lstSort.Sort();  8   9             List<int> lstIndex = new List<int>(); 10             for (int i = 0; i < lstSort.Count; i++) 11             { 12                 int index = lstOrg.IndexOf(lstSort[i]); 13                 while (lstIndex.IndexOf(index) >= 0) 14                 { 15                     index = lstOrg.IndexOf(lstSort[i], index + 1); 16                 } 17                 lstIndex.Add(index); 18                 Console.Write("({0},{1})", index, lstSort[i]); 19             } 34             Console.ReadLine();    
 1             int[] arrInt = new int[] { 11, 38, 12, 9, 234, 24, 441, 24, 45, 35 };  2   3             //Dictionary.OrderBy()  4             Dictionary<int, int> dic = new Dictionary<int, int>();  5             for (int i = 0; i < arrInt.Length; i++)  6             {  7                 dic.Add(i, arrInt[i]);  8             }  9             dic = dic.OrderBy(o => o.Value).ToDictionary(p => p.Key, o => o.Value); 10             foreach (var item in dic) 11             { 12                 Console.Write("({0},{1})", item.Key, item.Value); 13             } 14  15             Console.ReadLine();

输出正常!

总觉得应该有很方便的方法来实现,奈何想不出来。。。

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!