Linq在Array,List,Dictionary中的应用
Linq在Array,List,Dictionary中的应用
今天在实际工作中需要对array,list,dictionary进行排序,试一试linq,发现非常好用,代码如下:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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 }