LINQ的一些技巧 (转)

1.数组初始化

大小为10的数组,每个元素值都是-1
int[] a = Enumerable.Repeat(-1, 10).ToArray();

大小为10的数组,从0至9递增

int[] b = Enumerable.Range(0, 10).ToArray();

大小为10的数组,从100,110,120,...,190

int[] c = Enumerable.Range(0, 10).Select(i => 100 + 10 * i).ToArray();

2.生成随机数序列

生成10个范围在10-100的随机数

Random rand = new Random();
int [] randomSeq= randomSeq = Enumerable.Repeat(0, 10).Select(i => rand.Next(10,100)).ToArray();

3.集合类型转换

int集合转成string集合

List<int> intList = new List<int> { 1, 2, 3, 4, 5, 5 };
List<string> strList = new List<string>(intList.Cast<string>());

反过来,把string集合转成int集合

List<int> a = strList.Select(o => int.Parse(o)).ToList();

4.数组倒序

int [] arr = { 1, 2, 3, 4, 5};
arr.Reverse();

现在arr的元素已经是5,4,3,2,1了

原文地址:https://www.cnblogs.com/luluping/p/1215579.html