当前位置: 移动技术网 > IT编程>开发语言>c# > C# 数组排序带索引

C# 数组排序带索引

2019年08月26日  | 移动技术网IT编程  | 我要评论

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

输出正常!

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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网