Linq在Array,List,Dictionary中的应用

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

转载于:https://www.cnblogs.com/Johar/p/5686644.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值