今天在实际工作中需要对array,list,dictionary进行排序,试一试linq,发现非常好用,代码如下:
class="code_img_closed" src="/Upload/Images/2016072005/0015B68B3C38AA5B.gif" alt="" />logs_code_hide('68f39079-005b-4139-b9e8-334e841371fd',event)" src="/Upload/Images/2016072005/2B1B950FA3DF188F.gif" alt="" />1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Text.RegularExpressions; 6 7 namespace Test 8 { 9 class Program 10 { 11 static void Main(string[] args) 12 { 13 Console.WriteLine("Hello world!"); 14 string inputStr = " abf dcf frgt "; 15 inputStr = Regex.Replace(inputStr.Trim(), " {2,}", " "); 16 Console.WriteLine(inputStr); 17 18 int[] num = { 1, 2, 3, 4, 5, 5, 6, 1, 3, 2 }; 19 //Array.Sort(num); 20 var nums = (from l in num orderby l select l).ToArray(); 21 Console.Write("Array:\n"); 22 foreach (int i in nums) 23 Console.Write(i.ToString()); 24 Console.Write("\nList:\n"); 25 List<int> list = new List<int>() {1,2,1,9,3,2,7 }; 26 list = (from l in list orderby l select l).ToList(); 27 foreach (var l in list) 28 Console.Write(l); 29 Dictionary<int, int> counts = new Dictionary<int, int>() { {1,2},{2,3},{3,1}}; 30 //var results = (from d in counts orderby d.Value descending select d).Take(2).ToDictionary(k => k.Key, v => v.Value); 31 var results = (from d in counts orderby d.Value descending select d.Key).Take(2).ToArray(); 32 Console.Write("\nDictionary:\n"); 33 foreach (var d in results) 34 Console.WriteLine(d); 35 36 Console.ReadKey(); 37 } 38 } 39 }View Code
canC4fHf5VmcOEO6+H0loNyZpncE5/C4CANdI97NBzmXvY8tssBuXYTnVtsZW5f985W8+V39l29uf/vlf/PznP59qX7PSQ9/G3BOb+dKFDjCdbtM7fjf2/IYfx+YO8Lf0XLt8D3QnAQCYwNiqfPTo0Q9/+MO/3dK9e/fefffdHe5+6Do9wZkPQG9V7nxvd3884J7f8OPY3EH+lp5Z7dsh7yQAAFMYW5UcgnGXMTmmDXNlrE4vPj09Tc6yBADgmKnKq2T/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