C# 数组排序带索引

0
5

想到了两种方法来实现,分别利用了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();

输出正常!

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

<

发布回复

请输入评论!
请输入你的名字