程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> Linq在Array,List,Dictionary中的應用,linqdictionary

Linq在Array,List,Dictionary中的應用,linqdictionary

編輯:C#入門知識

Linq在Array,List,Dictionary中的應用,linqdictionary


Linq在Array,List,Dictionary中的應用

今天在實際工作中需要對array,list,dictionary進行排序,試一試linq,發現非常好用,代碼如下:

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

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved