码迷,mamicode.com
首页 > 其他好文 > 详细

Linq在Array,List,Dictionary中的应用

时间:2016-07-19 23:52:13      阅读:365      评论:0      收藏:0      [点我收藏+]

标签:

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

技术分享

Linq在Array,List,Dictionary中的应用

标签:

原文地址:http://www.cnblogs.com/Johar/p/5686644.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!